#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define maxn 4005
#define mod 1000000007
int h, w, d[maxn][maxn], dx[] = {-1, 1, 0, 0}, dy[] = {0, 0, -1, 1};
char a[maxn][maxn];
bool inside(int x, int y) {
return (x >= 1 && x <= h && y >= 1 && y <= w && a[x][y] != '.');
}
void solve() {
cin >> h >> w;
for (int i = 1; i <= h; i += 1) for (int j = 1; j <= w; j += 1) {
cin >> a[i][j];
}
memset(d, 0x3f, sizeof d);
deque<tuple<int, int, int>> dq;
int ans = 1;
d[1][1] = 1;
dq.push_back({1, 1, d[1][1]});
while (dq.size()) {
auto [x, y, dist] = dq.front();
dq.pop_front();
ans = max(ans, d[x][y]);
// cout << x << ' ' << y << '\n';
if (dist > d[x][y]) {
continue;
}
for (int i = 0; i < 4; i += 1) {
int newx = x + dx[i], newy = y + dy[i];
if (inside(newx, newy)) {
if (a[x][y] == a[newx][newy]) {
if (d[newx][newy] > dist) {
d[newx][newy] = dist;
dq.push_front({newx, newy, d[newx][newy]});
}
}
else {
if (d[newx][newy] > dist + 1) {
d[newx][newy] = dist + 1;
dq.push_back({newx, newy, d[newx][newy]});
}
}
}
}
}
cout << ans;
return;
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int test_case = 1;
// cin >> test_case;
for (int i = 1; i <= test_case; i += 1) {
solve();
}
return 0;
}
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |