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;
const int N=4000;
int n, m;
string grid[N];
int par[N*N];
int dx[]={0, 0, 1, -1};
int dy[]={1, -1, 0, 0};
vector<int> adj[N*N];
int find(int x){ return par[x]==x?x:par[x]=find(par[x]); }
void join(int x, int y){
int a=find(x);
int b=find(y);
par[a]=b;
}
int main(){
cin.tie(0)->sync_with_stdio(0);
cin >> n >> m;
for(int i=0; i<n; i++){
for(int j=0; j<m; j++) par[i*m+j]=i*m+j;
cin >> grid[i];
}
for(int i=0; i<n; i++){
for(int j=0; j<m; j++){
if(grid[i][j]=='*') continue;
for(int k=0; k<4; k++){
int x=i+dx[k];
int y=j+dy[k];
if(x<0 || x==n || y<0 || y==m || grid[x][y]!=grid[i][j]) continue;
join(m*i+j, m*x+y);
}
}
}
for(int i=0; i<n; i++){
for(int j=0; j<m; j++){
if(grid[i][j]=='*') continue;
for(int k=0; k<4; k++){
int x=i+dx[k];
int y=j+dy[k];
if(x<0 || x==n || y<0 || y==m || grid[x][y]==grid[i][j] || grid[x][y]=='*') continue;
adj[find(m*i+j)].push_back(find(m*x+y));
adj[find(m*x+y)].push_back(find(m*i+j));
}
}
}
for(int i=0; i<n*m; i++){
if(find(i)!=i) continue;
sort(adj[i].begin(), adj[i].end());
adj[i].erase(unique(adj[i].begin(), adj[i].end()), adj[i].end());
// for(int k:adj[i]) cout << i << " " << k << "\n";
}
queue<int> q;
q.push(find(0));
vector<int> vis(n*m);
for(; !q.empty(); q.pop()){
int x=q.front();
for(int k:adj[x]){
if(!vis[k] && k!=find(0)){
vis[k]=vis[x]+1;
// cout << "vis[" << k << "] = " << vis[k] << "\n";
q.push(k);
}
}
}
cout << *max_element(vis.begin(), vis.end())+1;
}
// when its been a long time since goodbye
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |