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;
int main() {
int N, M;
cin >> N >> M;
vector<string> S(N);
for (auto &v : S) {
cin >> v;
}
vector<vector<int>> up(N, vector<int>(M, -1)), down(N, vector<int>(M, -1)), left(N, vector<int>(M, -1)), right(N, vector<int>(M, -1));
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
if (S[i][j] != '#') {
up[i][j] = (i == 0 ? -1 : up[i - 1][j]) + 1;
left[i][j] = (j == 0 ? -1 : left[i][j - 1]) + 1;
}
}
}
for (int i = N - 1; i >= 0; i--) {
for (int j = M - 1; j >= 0; j--) {
if (S[i][j] != '#') {
down[i][j] = (i == N - 1 ? -1 : down[i + 1][j]) + 1;
right[i][j] = (j == M - 1 ? -1 : right[i][j + 1]) + 1;
}
}
}
queue<pair<int, int>> q;
vector<vector<int>> dist(N, vector<int>(M, INT_MAX));
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
if (S[i][j] == 'S') {
dist[i][j] = 0;
q.push({i, j});
}
}
}
while (!q.empty()) {
auto [x, y] = q.front();
q.pop();
for (auto [i, j] : vector<pair<int, int>> {{x - 1, y}, {x, y - 1}, {x + 1, y}, {x, y + 1},
{x - up[x][y], y}, {x, y - left[x][y]}, {x + down[x][y], y}, {x, y + right[x][y]}}) {
if (up[x][y] > 1 && i == x - up[x][y] && down[x][y] != 0) {
continue;
}
if (down[x][y] > 1 && i == x + down[x][y] && up[x][y] != 0) {
continue;
}
if (left[x][y] > 1 && j == y - left[x][y] && right[x][y] != 0) {
continue;
}
if (right[x][y] > 1 && j == y + right[x][y] && left[x][y] != 0) {
continue;
}
if (i >= 0 && j >= 0 && i < N && j < M && S[i][j] != '#' && dist[i][j] == INT_MAX) {
dist[i][j] = dist[x][y] + 1;
q.push({i, j});
}
}
}
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
if (S[i][j] == 'C') {
cout << dist[i][j] << "\n";
exit(0);
}
}
}
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |