This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define endl '\n';
const ll MOD = 1e9 + 7;
const ll MOD2 = 998244353;
char grid[4000][4000];
int dist[4000][4000];
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int n, m;
cin >> n >> m;
for (int i = 0;i < n;i++) {
for (int j = 0;j < m;j++) {
cin >> grid[i][j];
dist[i][j] = 1e9;
}
}
deque<array<int, 3>> q;
q.push_back({0, 0, 1});
while (!q.empty()) {
array<int, 3> s = q.front();
q.pop_front();
dist[s[0]][s[1]] = min(s[2], dist[s[0]][s[1]]);
if (s[0] > 0) {
if (grid[s[0]-1][s[1]] != '.') {
if (grid[s[0]-1][s[1]] == grid[s[0]][s[1]]) {
if (dist[s[0]-1][s[1]] > s[2]) {
q.push_front({s[0]-1, s[1], s[2]});
}
} else {
if (dist[s[0]-1][s[1]] > s[2]+1) {
q.push_back({s[0]-1, s[1], s[2]+1});
}
}
}
}
if (s[0] < n-1) {
if (grid[s[0]+1][s[1]] != '.') {
if (grid[s[0]+1][s[1]] == grid[s[0]][s[1]]) {
if (dist[s[0]+1][s[1]] > s[2]) {
q.push_front({s[0]+1, s[1], s[2]});
}
} else {
if (dist[s[0]+1][s[1]] > s[2]+1) {
q.push_back({s[0]+1, s[1], s[2]+1});
}
}
}
}
if (s[1] > 0) {
if (grid[s[0]][s[1]-1] != '.') {
if (grid[s[0]][s[1]-1] == grid[s[0]][s[1]]) {
if (dist[s[0]][s[1]-1] > s[2]) {
q.push_front({s[0], s[1]-1, s[2]});
}
} else {
if (dist[s[0]][s[1]-1] > s[2]+1) {
q.push_back({s[0], s[1]-1, s[2]+1});
}
}
}
}
if (s[1] < m-1) {
if (grid[s[0]][s[1]+1] != '.') {
if (grid[s[0]][s[1]+1] == grid[s[0]][s[1]]) {
if (dist[s[0]][s[1]+1] > s[2]) {
q.push_front({s[0], s[1]+1, s[2]});
}
} else {
if (dist[s[0]][s[1]+1] > s[2]+1) {
q.push_back({s[0], s[1]+1, s[2]+1});
}
}
}
}
}
int out = 0;
for (int i = 0;i < n;i++) {
for (int j = 0;j < m;j++) {
if (dist[i][j] < 1e9) {
out = max(out, dist[i][j]);
}
}
}
cout << out << endl;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |