#include <algorithm>
#include <iostream>
using namespace std;
const int N = 4000;
const int M = 4000;
const int INF = 0x3f3f3f3f;
const int di[] = { -1, 1, 0, 0 };
const int dj[] = { 0, 0, -1, 1 };
char cc[N][M + 1];
int dd[N][M], qu[N * M * 2];
int main() {
ios_base::sync_with_stdio(false), cin.tie(NULL);
int n, m; cin >> n >> m;
for (int i = 0; i < n; i++)
cin >> cc[i];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
dd[i][j] = INF;
int cnt = n * m; dd[0][0] = 1, qu[cnt++] = 0;
for (int h = n * m; h < cnt; h++) {
int ij = qu[h], i = ij / m, j = ij % m, d = dd[i][j];
for (int z = 0; z < 4; z++) {
int i_ = i + di[z], j_ = j + dj[z];
if (0 <= i_ && i_ < n && 0 <= j_ && j_ < m && cc[i_][j_] != '.') {
int ij_ = i_ * m + j_;
if (cc[i][j] == cc[i_][j_]) {
if (dd[i_][j_] > d)
dd[i_][j_] = d, qu[h--] = ij_;
} else {
if (dd[i_][j_] > d + 1)
dd[i_][j_] = d + 1, qu[cnt++] = ij_;
}
}
}
}
int ans = 0;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
if (cc[i][j] != '.')
ans = max(ans, dd[i][j]);
cout << ans << '\n';
return 0;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |