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 mxN = 4000;
int H, W, id[mxN][mxN];
char grid[mxN][mxN];
int dx[4]{1, -1, 0, 0}, dy[4]{0, 0, 1, -1};
vector<set<int>> adj;
vector<int> dist;
void ff(int r, int c, int x) {
id[r][c] = x;
for (int i=0; i<4; ++i) {
int nr = r + dx[i], nc = c + dy[i];
if (nr >= 0 && nr < H && nc >= 0 && nc < W &&
grid[nr][nc] == grid[r][c] && !id[nr][nc]) {
ff(nr, nc, x);
}
}
}
void ff2(int r, int c, int x) {
id[r][c] = 0;
for (int i=0; i<4; ++i) {
int nr = r + dx[i], nc = c + dy[i];
if (nr >= 0 && nr < H && nc >= 0 && nc < W && id[nr][nc]) {
if (id[nr][nc] != x)
adj[x-1].insert(id[nr][nc]-1);
else
ff2(nr, nc, x);
}
}
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cin >> H >> W;
for (int i=0; i<H; ++i)
for (int j=0; j<W; ++j)
cin >> grid[i][j];
int cur = 0;
for (int i=0; i<H; ++i) {
for (int j=0; j<W; ++j) {
if (!id[i][j] && grid[i][j] != '.')
ff(i, j, ++cur);
}
}
adj.resize(cur);
dist.resize(cur, 2e9);
for (int i=0; i<H; ++i) {
for (int j=0; j<W; ++j) {
if (id[i][j]) {
ff2(i, j, id[i][j]);
}
}
}
queue<int> q;
q.push(0);
dist[0] = 0;
while (!q.empty()) {
int x = q.front();
q.pop();
for (int u : adj[x]) {
if (dist[u] == 2e9) {
dist[u] = dist[x] + 1;
q.push(u);
}
}
}
int ans = 0;
for (int i : dist)
ans = max(ans, i);
cout << ans + 1 << '\n';
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |