#include <bits/stdc++.h>
using namespace std;
#define int long long
const int dx[4] = {1, -1, 0, 0};
const int dy[4] = {0, 0, 1, -1};
const int maxn = 4005;
char a[maxn][maxn];
int d[maxn][maxn];
void solve(){
int n, m; cin >> n >> m;
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m; j++) cin >> a[i][j];
}
deque<array<int, 3>> dq;
dq.push_back({1, 1, 1});
vector<vector<int>> d(n + 1, vector<int>(m + 1, 1e9));
d[1][1] = 1;
while(!dq.empty()){
auto[curd, x, y] = dq.front();
dq.pop_front();
if (curd > d[x][y]) continue;
for (int k = 0; k < 4; k++){
int r = x + dx[k], c = y + dy[k];
if (r < 1 || c < 1 || r > n || c > m || a[r][c] == '.') continue;
if (d[r][c] > d[x][y] + (a[r][c] != a[x][y])) {
d[r][c] = d[x][y] + (a[r][c] != a[x][y]);
if (a[r][c] == a[x][y]) dq.push_front({d[r][c], r, c});
else dq.push_back({d[r][c], r, c});
}
}
}
int res = 0;
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m; j++){
if(d[i][j] < 5e8) res = max(res, d[i][j]);
}
}
cout << res;
}
signed main() {
ios_base::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
solve();
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |