#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const ll MOD = 1e9 + 7;
using pii = pair<int, int>;
bool in_bounds(int x, int y, int r, int c) {
return x >= 0 && x < r && y >= 0 && y < c;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int h, w;
cin >> h >> w;
vector<vector<char>> grid(h, vector<char>(w));
for (int i = 0; i < h; i++) for (int j = 0; j < w; j++) cin >> grid.at(i).at(j);
vector<vector<int>> ans(h, vector<int>(w, INT_MAX));
deque<pii> dq;
dq.push_back({0, 0});
ans.at(0).at(0) = 1;
while (!dq.empty()) {
pii p = dq.front();
int x = p.first, y = p.second;
dq.pop_front();
for (int k = -2; k < 2; k++) {
int dx = k % 2, dy = (k + 1) % 2;
if (in_bounds(x + dx, y + dy, h, w)) {
if (grid.at(x + dx).at(y + dy) == '.') continue;
int new_dist = ans.at(x).at(y) + (grid.at(x).at(y) != grid.at(x + dx).at(y + dy));
if (new_dist < ans.at(x + dx).at(y + dy)) {
ans.at(x + dx).at(y + dy) = new_dist;
if (grid.at(x).at(y) != grid.at(x + dx).at(y + dy)) dq.push_back({x + dx, y + dy});
else dq.push_front({x + dx, y + dy});
}
}
}
}
int final_ans = 0;
for (int i = 0; i < h; i++) for (int j = 0; j < w; j++) if (ans.at(i).at(j) != INT_MAX) final_ans = max(final_ans, ans.at(i).at(j));
cout << final_ans << endl;
return 0;
}
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |