#include <iostream>
#include <vector>
#include <algorithm>
#include <cassert>
#include <queue>
using ll = long long;
#define debug(x) #x << " = " << x << '\n'
const int NMAX = 4000;
const int dx[4] = {-1, 0, +1, 0};
const int dy[4] = {0, -1, 0, +1};
char a[NMAX + 2][NMAX + 2];
int dist[NMAX + 2][NMAX + 2];
int main() {
#ifdef LOCAL
freopen("input.txt", "r", stdin);
#endif
std::ios_base::sync_with_stdio(false);
std::cin.tie(0);
int n, m;
std::cin >> n >> m;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
std::cin >> a[i][j];
}
}
int pasite = 0;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
if (a[i][j] != '.') {
pasite++;
}
dist[i][j] = n * m + 1;
}
}
std::deque<std::pair<int, int>> deq;
dist[1][1] = 1;
deq.push_back({1, 1});
while (!deq.empty()) {
auto [x, y] = deq.front();
deq.pop_front();
for (int k = 0; k < 4; k++) {
int xx = x + dx[k];
int yy = y + dy[k];
if (xx > 0 && yy > 0 && xx <= n && yy <= m) {
if (a[x][y] == a[xx][yy] && dist[x][y] < dist[xx][yy]) {
dist[xx][yy] = dist[x][y];
deq.push_front({xx, yy});
} else if (a[x][y] != a[xx][yy] && dist[x][y] + 1 < dist[xx][yy]) {
dist[xx][yy] = dist[x][y] + 1;
deq.push_back({xx, yy});
}
}
}
}
int answer = 0;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
answer = std::max(answer, dist[i][j]);
}
}
std::cout << answer;
return 0;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |