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];
bool vis[mxN][mxN];
int dx[4]{1, -1, 0, 0}, dy[4]{0, 0, 1, -1};
vector<int> dist;
queue<pair<int, int>> q;
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) {
vis[r][c] = true;
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 &&
!vis[nr][nc] && grid[nr][nc] != '.') {
if (grid[nr][nc] != grid[r][c]) {
if (dist[id[nr][nc]] == 2e9) {
dist[id[nr][nc]] = dist[id[r][c]] + 1;
q.push({nr, nc});
}
} else {
ff2(nr, nc);
}
}
}
}
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);
}
}
dist.resize(cur+1, 2e9);
queue<pair<int, int>> q;
q.push({0, 0});
dist[1] = 0;
while (!q.empty()) {
int r = q.front().first;
int c = q.front().second;
q.pop();
ff2(r, c);
}
int ans = 0;
for (int i=1; i<=cur; ++i)
ans = max(ans, dist[i]);
cout << ans + 1 << '\n';
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |