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;
#define ll long long
#define ar array
#define f first
#define s second
#define mpr make_pair
#define pb push_back
#define lb lower_bound
#define ub upper_bound
#define all(x) x.begin(), x.end()
#define FOR(i, a, b) for(auto i = a; i < b; i++)
#define FORD(i, a, b) for(auto i = a - 1; i >= b; i--)
#define trav(x, v) for(auto x : v)
#define fastio ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
#define fileio freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout);
// --------------- SOLUTION --------------- //
const int INF = 1e9;
int n, m;
char a[501][501];
int d[501][501];
set <pair<int, pair<int, int>>> s;
char dir[4] = {'W', 'S', 'E', 'N'};
bool valid(int x, int y) {
return (x >= 0 && x < n && y >= 0 && y < m);
}
void read() {
cin >> n >> m;
FOR(i, 0, n) {
FOR(j, 0, m) {
cin >> a[i][j];
}
}
}
void make_inf() {
FOR(i, 0, n) {
FOR(j, 0, m) {
d[i][j] = INF;
}
}
}
void djk() {
d[0][0] = 0;
s.insert({0, {0, 0}});
while (!s.empty()) {
auto it = s.begin();
int dist = (*it).f;
int x = (*it).s.f;
int y = (*it).s.s;
s.erase(it);
if (a[x][y] == 'X') {
continue;
}
FOR(i, 0, 4) {
int cnt = 0;
int xx = 0, yy = 0;
if (a[x][y] == dir[i]) cnt = 0;
else if (a[x][y] == dir[(i + 1) % 4]) cnt = 1;
else if (a[x][y] == dir[(i + 2) % 4]) cnt = 2;
else cnt = 3;
if (dir[i] == 'W') xx = 0, yy = -1;
else if (dir[i] == 'S') xx = 1, yy = 0;
else if (dir[i] == 'E') xx = 0, yy = 1;
else xx = -1, yy = 0;
if (valid(x + xx, y + yy) && d[x + xx][y + yy] > dist + cnt) {
s.erase({d[x + xx][y + yy], {x + xx, y + yy}});
d[x + xx][y + yy] = dist + cnt;
s.insert({d[x + xx][y + yy], {x + xx, y + yy}});
}
}
}
}
void display() {
if(d[n - 1][m - 1] != INF)
cout << d[n - 1][m - 1] << endl;
else
cout << -1 << endl;
}
void solve() {
read();
make_inf();
djk();
display();
}
int main() {
fastio;
//fileio;
int tests = 1;
// cin >> tests;
while (tests--) {
solve();
}
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... |