This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
using namespace std;
int n, m;
const int dx[4]={0, 0, 1, -1};
const int dy[4]={1, -1, 0, 0};
char a[4005][4005];
bool visited[4005][4005];
int d[4005][4005];
int ans=1;
using P=pair<pair<int, int>, int>;
deque<P>dq;
bool check(int i, int j){
if (a[i][j]!='.' && 1<=i && i<=n && 1<=j && j<=m) return true;
else return false;
}
void bfs(){
dq.push_back({{1, 1}, 0});
d[1][1]=1;//vi ton 1 con vat;
while (!dq.empty()){
int distance=dq.front().second;
int u=dq.front().first.first;
int v=dq.front().first.second;
dq.pop_front();
if (visited[u][v]) continue;
visited[u][v]=true;
ans=max(ans, distance);
for (int t=0; t<4; t++){
int ii=u+dx[t];
int jj=v+dy[t];
if (check(ii, jj)==false || visited[ii][jj]) continue;
if (a[u][v]!=a[ii][jj]){
if (d[u][v]+1<d[ii][jj]){
d[ii][jj]=d[u][v]+1;
dq.push_back({{ii, jj}, d[ii][jj]});
}
}else{
if (d[u][v]<d[ii][jj]){
d[ii][jj]=d[u][v];
dq.push_front({{ii, jj}, d[ii][jj]});
}
}
}
}
cout<<ans;
}
int main(){
cin>>n>>m;
for (int i=1;i <=n; i++){
for (int j=1; j<=m; j++){
cin>>a[i][j];
if (i==1 && j==1) d[i][j]=1;
else d[i][j]=1e9;
}
}
bfs();
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |