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;
const int INF = 2147483647;
int main() {
int H, W;
cin >> H >> W;
vector<string> meadow(H);
for (int i = 0; i < H; i++) cin >> meadow[i];
vector<vector<int>> dists(H, vector<int>(W, INF));
dists[0][0] = 1;
deque<pair<int, int>> q; q.push_back({0, 0});
pair<int, int> cur; char curC, newC;
while (!q.empty()) {
cur = q.front();
q.pop_front();
curC = meadow[cur.first][cur.second];
if (cur.first > 0) {
newC = meadow[cur.first - 1][cur.second];
if (newC == curC) {
if (dists[cur.first][cur.second] < dists[cur.first - 1][cur.second]) {
dists[cur.first - 1][cur.second] = dists[cur.first][cur.second];
q.push_front({cur.first - 1, cur.second});
}
} else if (newC != '.') {
if (dists[cur.first][cur.second] + 1 < dists[cur.first - 1][cur.second]) {
dists[cur.first - 1][cur.second] = dists[cur.first][cur.second] + 1;
q.push_back({cur.first - 1, cur.second});
}
}
}
if (cur.first < H - 1) {
newC = meadow[cur.first + 1][cur.second];
if (newC == curC) {
if (dists[cur.first][cur.second] < dists[cur.first + 1][cur.second]) {
dists[cur.first + 1][cur.second] = dists[cur.first][cur.second];
q.push_front({cur.first + 1, cur.second});
}
} else if (newC != '.') {
if (dists[cur.first][cur.second] + 1 < dists[cur.first + 1][cur.second]) {
dists[cur.first + 1][cur.second] = dists[cur.first][cur.second] + 1;
q.push_back({cur.first + 1, cur.second});
}
}
}
if (cur.second > 0) {
newC = meadow[cur.first][cur.second - 1];
if (newC == curC) {
if (dists[cur.first][cur.second] < dists[cur.first][cur.second - 1]) {
dists[cur.first][cur.second - 1] = dists[cur.first][cur.second];
q.push_front({cur.first, cur.second - 1});
}
} else if (newC != '.') {
if (dists[cur.first][cur.second] + 1 < dists[cur.first][cur.second - 1]) {
dists[cur.first][cur.second - 1] = dists[cur.first][cur.second] + 1;
q.push_back({cur.first, cur.second - 1});
}
}
}
if (cur.second < W - 1) {
newC = meadow[cur.first][cur.second + 1];
if (newC == curC) {
if (dists[cur.first][cur.second] < dists[cur.first][cur.second + 1]) {
dists[cur.first][cur.second + 1] = dists[cur.first][cur.second];
q.push_front({cur.first, cur.second + 1});
}
} else if (newC != '.') {
if (dists[cur.first][cur.second] + 1 < dists[cur.first][cur.second + 1]) {
dists[cur.first][cur.second + 1] = dists[cur.first][cur.second] + 1;
q.push_back({cur.first, cur.second + 1});
}
}
}
}
int ans = 1;
for (int i = 0; i < H; i++) {
for (int j = 0; j < W; j++) {
if (dists[i][j] != INF) ans = max(ans, dists[i][j]);
}
}
cout << ans << "\n";
return 0;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |