#include <bits/stdc++.h>
#define ff first
#define ss second
#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()
#define sz(x) (int)(x).size()
using namespace std;
using ll = long long;
using pii = pair<int, int>;
const char nl = '\n';
const ll LINF = 0x3f3f3f3f3f3f3f3f;
const int INF = 0x3f3f3f3f;
int main() {
ios::sync_with_stdio(0), cin.tie(0);
int n, m; cin >> n >> m;
vector<vector<char>> ma(n + 1, vector<char>(m + 1));
for (int i = 1; i <= n; i++) {
string s; cin >> s; s = '0' + s;
for (int j = 1; j <= m; j++) {
ma[i][j] = s[j];
}
}
using T = pair<int, pii>;
priority_queue<T, vector<T>, greater<T>> pq;
vector<vector<int>> dist(n + 1, vector<int>(m + 1, INF));
pq.push({1, {1, 1}}); dist[1][1] = 1;
vector<int> dx = {-1, 1, 0, 0};
vector<int> dy = {0, 0, -1, 1};
auto ok = [&](int x, int y) -> bool {
return 1 <= x && x <= n && 1 <= y && y <= m && ma[x][y] != '.';
};
while (!pq.empty()) {
auto [d, v] = pq.top(); pq.pop();
auto [x, y] = v;
if (dist[x][y] != d) continue;
for (int d = 0; d < 4; d++) {
int nx = x + dx[d];
int ny = y + dy[d];
if (!ok(nx, ny)) continue;
int dd = (ma[x][y] == ma[nx][ny] ? 0 : 1);
if (d + dd < dist[nx][ny]) {
dist[nx][ny] = d + dd;
pq.push({dist[nx][ny], {nx, ny}});
}
}
}
int ans = 1;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
if (dist[i][j] != INF)
ans = max(ans, dist[i][j]);
cout << ans << nl;
return 0;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |