#include <bits/stdc++.h>
#define maxn 4005
#define fi first
#define se second
using namespace std;
using ii = pair<int, int>;
int n, m;
char a[maxn][maxn];
int cl[maxn][maxn];
int dv[4] = {0, 1, 0, -1};
int dh[4] = {1, 0, -1, 0};
int nho[maxn*maxn], id = 0;
void bfs(int ox, int oy) {
queue<ii> q;
q.push(ii{ox, oy});
cl[ox][oy] = ++id;
while (!q.empty()) {
auto [u, v] = q.front(); q.pop();
for (int k = 0; k < 4; k++) {
int i = u + dv[k], j = v + dh[k];
if (1 <= i && 1 <= j && i <= n && j <= m && !cl[i][j] && a[i][j] == a[u][v]) {
cl[i][j] = 1;
q.push(ii{i, j});
}
}
}
}
vector<int> adj[maxn*maxn];
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL);
cin >> n >> m;
for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) cin >> a[i][j];
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
if (a[i][j] != '.' && !cl[i][j]) bfs(i, j);
map<ii, int> rem;
for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) for (int k = 0; k < 4; k++) {
int u = i + dv[k], v = j + dh[k];
if (1 <= u && u <= n && 1 <= v && v <= m && a[i][j] != '.' && a[u][v] != '.' && a[u][v] != a[i][j]) {
if (rem[ii{cl[i][j], cl[u][v]}]) continue;
adj[cl[i][j]].emplace_back(cl[u][v]);
adj[cl[u][v]].emplace_back(cl[i][j]);
rem[ii{cl[i][j], cl[u][v]}] = rem[ii{cl[u][v], cl[i][j]}] = 1;
}
}
queue<int> q;
nho[1] = 1;
q.push(1);
while (!q.empty()) {
int u = q.front(); q.pop();
for (int v : adj[u])
if (!nho[v]) {
nho[v] = nho[u]+1;
q.push(v);
}
}
cout << *max_element(nho + 1, nho + id + 1);
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |