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>
#define N 4003
#define f first
#define s second
using namespace std;
typedef pair<int, int> pii;
int n, m, ans, cnt, ok[N][N], dx[4] = {0, 0, 1, -1}, dy[4] = {1, -1, 0, 0};
int id[N][N], pai[N*N], dist[N*N];
char mat[N][N], T;
vector<int> grafo[N*N];
void dfs(int x, int y, int &p)
{
//cout<<"DFS "<<x<<" "<<y<<"\n";
ok[x][y] = 1;
pai[id[x][y]] = p;
for(int pp = 0; pp < 4; pp++)
{
int a = x + dx[pp], b = y + dy[pp];
if(!a or !b or a > n or b > m or mat[a][b] != mat[x][y] or ok[a][b]) continue;
//cout<<"VIZ "<<x<<" "<<y<<" "<<a<<" "<<b<<"\n";
dfs(a, b, p);
}
}
int main()
{
//ios::sync_with_stdio(false); cin.tie(0);
cin>>n>>m;
for(int i = 1; i <= n; i++)
{
for(int j = 1; j <= m; j++)
{
cin>>mat[i][j];
id[i][j] = ++cnt;
pai[id[i][j]] = id[i][j];
}
}
for(int i = 1; i <= n; i++)
{
for(int j = 1; j <= m; j++)
{
if(mat[i][j] == '.' or ok[i][j]) continue;
//cout<<"INI "<<i<<" "<<j<<"\n";
dfs(i, j, id[i][j]);
//cout<<"FIM "<<i<<" "<<j<<"\n";
}
}
for(int i = 1; i <= n; i++)
{
for(int j = 1; j <= m; j++)
{
if(mat[i][j] == '.') continue;
for(int p = 0; p < 4; p++)
{
int a = i + dx[p], b = j + dy[p];
if(!a or !b or a > n or b > m) continue;
if(mat[a][b] != mat[i][j] and mat[a][b] != '.')
{
int u = pai[id[a][b]], v = pai[id[i][j]];
grafo[u].push_back(v);
}
}
}
}
queue<int> fila;
dist[pai[id[1][1]]] = 1;
fila.push(pai[id[1][1]]);
while(!fila.empty())
{
int x = fila.front();
ans = max(ans, dist[x]);
fila.pop();
for(auto v: grafo[x])
{
if(dist[v] == 0)
{
dist[v] = dist[x] + 1;
fila.push(v);
}
}
}
cout<<ans<<"\n";
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |