#include <bits/stdc++.h>
using namespace std;
struct Node {
int x, y, w;
};
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int H, W;
cin >> H >> W;
vector<string> grid(H);
for (int i = 0; i < H; i++) cin >> grid[i];
vector<vector<int>> dist(H, vector<int>(W, 1e9));
const int dx[4] = {-1, 1, 0, 0};
const int dy[4] = {0, 0, -1, 1};
deque<Node> dq;
dq.push_front({0, 0, 0});
dist[0][0] = 0;
while (!dq.empty()) {
auto [x, y, w] = dq.front();
dq.pop_front();
for (int dir = 0; dir < 4; dir++) {
int nx = x + dx[dir];
int ny = y + dy[dir];
if (nx < 0 || ny < 0 || nx >= H || ny >= W) continue;
if (grid[nx][ny] == '.') continue;
int nw = (grid[x][y] != grid[nx][ny]);
if (dist[x][y] + nw < dist[nx][ny]) {
dist[nx][ny] = dist[x][y] + nw;
if (nw == 0) dq.push_front({nx, ny, nw});
else dq.push_back({nx, ny, nw});
}
}
}
int maxi = 0;
for (int i = 0; i < H; i++)
for (int j = 0; j < W; j++)
if (dist[i][j] != 1e9)
maxi = max(maxi, dist[i][j]);
cout << maxi + 1;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |