#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];
}
vector<vector<int>> dist(n + 1, vector<int>(m + 1, INF));
deque<pii> q;
q.push_front({1, 1});
dist[1][1] = 1;
auto val = [&](int x, int y) -> bool {
return 1 <= x && x <= n && 1 <= y && y <= m;
};
vector<int> dx = {-1, 1, 0, 0};
vector<int> dy = {0, 0, -1, 1};
while (!q.empty()) {
auto [x, y] = q.front(); q.pop_front();
for (int d = 0; d < 4; d++) {
int nx = x + dx[d];
int ny = y + dy[d];
if (!val(nx, ny)) continue;
int w = (ma[x][y] == ma[nx][ny] ? 0 : 1);
if (dist[x][y] + w < dist[nx][ny]) {
dist[nx][ny] = dist[x][y] + w;
if (w == 0)
q.push_front({nx, ny});
else
q.push_back({nx, ny});
}
}
}
int ans = 0;
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... |