#include <bits/stdc++.h>
using namespace std;
deque<tuple<int, int, int>> dq;
int h, w, dp[4010][4010], ans;
int dx[4] = {1, 0, -1, 0}, dy[4] = {0, 1, 0, -1};
char arr[4010][4010];
int main() {
cin.tie(0)->sync_with_stdio(0);
cin >> h >> w;
for(int i=0; i<4001; i++) for(int j=0; j<4001; j++) dp[i][j] = 1e8;
for(int i=0; i<h; i++) {
for(int j=0; j<w; j++) {
cin >> arr[i][j];
}
}
dq.push_front({0, 0, 0});
dp[0][0] = 0;
while(dq.size()) {
int cx = get<1>(dq.front());
int cy = get<2>(dq.front());
int cd = get<0>(dq.front());
dq.pop_front();
if(cx < 0 || cy < 0 || cx >= h || cy >= w) continue;
if(cd > dp[cx][cy]) continue;
for(int i=0; i<4; i++) {
int nx = cx+dx[i], ny = cy+dy[i], nd = cd+(arr[cx][cy] == arr[nx][ny] ? 0 : 1);
if(nx < 0 || ny < 0 || nx >= h || ny >= w || arr[nx][ny] == '.') continue;
if(nd < dp[nx][ny]) {
dp[nx][ny] = nd;
if(nd == cd) dq.push_front({nd, nx, ny});
else dq.push_back({nd, nx, ny});
}
}
}
for(int i=0; i<h; i++) {
for(int j=0; j<w; j++) {
if(dp[i][j] != 1e8) ans = max(ans, dp[i][j]);
}
}
cout << ans+1;
return 0;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |