#include <bits/stdc++.h>
using namespace std;
const int INF = 1e9;
int main() {
int n, m;
cin >> n >> m;
vector<vector<char>> grid(n+2, vector<char>(m+2, '*'));
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) cin >> grid[i][j];
}
vector<vector<int>> dist(n+2, vector<int>(m+2, INF));
dist[1][1] = 0;
deque<pair<int, int>> d;
d.push_front({1, 1});
int ans = 0;
while (!d.empty()) {
int i = d.front().first, j = d.front().second;
d.pop_front();
ans = max(ans, dist[i][j]);
vector<pair<int, int>> v;
v.push_back({i-1, j});
v.push_back({i+1, j});
v.push_back({i, j-1});
v.push_back({i, j+1});
for (auto p : v) {
if (grid[p.first][p.second] == '*') continue;
int w = (grid[p.first][p.second] != grid[i][j]);
if (dist[p.first][p.second] > dist[i][j]+w) {
dist[p.first][p.second] = dist[i][j]+w;
if (w) d.push_back(p);
else d.push_front(p);
}
}
}
cout << ans+1 << '\n';
return 0;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |