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>
#define f first
#define s second
#define int long long
using namespace std;
const int maxn = 510;
const int inf = 1e9;
char a[maxn][maxn];
int d[maxn][maxn], n, m;
vector<int> g[maxn * maxn];
signed main()
{
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n >> m;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
cin >> a[i][j];
}
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
d[i][j] = inf;
}
}
d[1][1] = 0;
priority_queue<pair<int, pair<int, int>>> pq;
pq.push({0, {1, 1}});
while(!pq.empty()) {
auto u = pq.top();
int c = u.f, x = u.s.f, y = u.s.s;
c = abs(c);
pq.pop();
if(a[x][y] == 'N') {
if(x - 1 >= 1 && d[x - 1][y] > c) {
d[x - 1][y] = c;
pq.push({-d[x - 1][y], {x - 1, y}});
}
if(y + 1 <= m && d[x][y + 1] > c + 1) {
d[x][y + 1] = c + 1;
pq.push({-d[x][y + 1], {x, y + 1}});
}
if(x + 1 <= n && d[x + 1][y] > c + 2) {
d[x + 1][y] = c + 2;
pq.push({-d[x + 1][y], {x + 1, y}});
}
if(y - 1 <= m && d[x][y - 1] > c + 3) {
d[x][y - 1] = c + 3;
pq.push({-d[x][y - 1], {x, y - 1}});
}
}
else if(a[x][y] == 'E') {
if(x - 1 >= 1 && d[x - 1][y] > c + 3) {
d[x - 1][y] = c + 3;
pq.push({-d[x - 1][y], {x - 1, y}});
}
if(y + 1 <= m && d[x][y + 1] > c) {
d[x][y + 1] = c;
pq.push({-d[x][y + 1], {x, y + 1}});
}
if(x + 1 <= n && d[x + 1][y] > c + 1) {
d[x + 1][y] = c + 1;
pq.push({-d[x + 1][y], {x + 1, y}});
}
if(y - 1 <= m && d[x][y - 1] > c + 2) {
d[x][y - 1] = c + 2;
pq.push({-d[x][y - 1], {x, y - 1}});
}
}
else if(a[x][y] == 'S') {
if(x - 1 >= 1 && d[x - 1][y] > c + 2) {
d[x - 1][y] = c + 2;
pq.push({-d[x - 1][y], {x - 1, y}});
}
if(y + 1 <= m && d[x][y + 1] > c + 3) {
d[x][y + 1] = c + 3;
pq.push({-d[x][y + 1], {x, y + 1}});
}
if(x + 1 <= n && d[x + 1][y] > c) {
d[x + 1][y] = c;
pq.push({-d[x + 1][y], {x + 1, y}});
}
if(y - 1 <= m && d[x][y - 1] > c + 1) {
d[x][y - 1] = c + 1;
pq.push({-d[x][y - 1], {x, y - 1}});
}
}
else if(a[x][y] == 'W') {
if(x - 1 >= 1 && d[x - 1][y] > c + 1) {
d[x - 1][y] = c + 1;
pq.push({-d[x - 1][y], {x - 1, y}});
}
if(y + 1 <= m && d[x][y + 1] > c + 2) {
d[x][y + 1] = c + 2;
pq.push({-d[x][y + 1], {x, y + 1}});
}
if(x + 1 <= n && d[x + 1][y] > c + 3) {
d[x + 1][y] = c + 3;
pq.push({-d[x + 1][y], {x + 1, y}});
}
if(y - 1 <= m && d[x][y - 1] > c) {
d[x][y - 1] = c;
pq.push({-d[x][y - 1], {x, y - 1}});
}
}
}
if(d[n][m] == inf)
cout << -1;
else
cout << d[n][m];
return 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... |