#include <bits/stdc++.h>
using namespace std;
#define el '\n'
#define ll long long
#define ld long double
#define ull unsigned long long
#define pll pair<long long, long long>
#define ppll pair< pair<long long, long long>, long long >
#define ff first
#define ss second
#define pb push_back
#define pf push_front
#define all(x) x.begin(), x.end()
const ll DIM = 507;
const ll INF = 1e18;
const ll mod = 1e9 + 7;
const ll maxlog = 20;
ll dist[DIM][DIM], a[DIM][DIM];
priority_queue<ppll> q;
const vector<ll> dx {-1, 0, 1, 0};
const vector<ll> dy {0, 1, 0, -1};
void solve() {
ll n, m;
cin >> n >> m;
for (int i=1; i<=n; i++) {
for (int j=1; j<=m; j++) {
char ch;
cin >> ch;
if (ch == 'N') a[i][j] = 0;
else if (ch == 'E') a[i][j] = 1;
else if (ch == 'S') a[i][j] = 2;
else if (ch == 'W') a[i][j] = 3;
else a[i][j] = -1;
dist[i][j] = INF;
}
}
dist[1][1] = 0;
q.push({{1, 1}, 0});
while (!q.empty()) {
ll x = q.top().ff.ff, y = q.top().ff.ss;
q.pop();
for (int t=0; t<4; t++) {
ll nx = x + dx[(a[x][y]+t)%4], ny = y + dy[(a[x][y]+t)%4];
if (nx < 1 || nx > n || ny < 1 || ny > m || (a[nx][ny] == -1 && (nx != n || ny != m)) ) continue;
if (dist[nx][ny] > dist[x][y] + t) {
dist[nx][ny] = dist[x][y] + t;
q.push({{nx, ny}, dist[nx][ny]});
}
}
}
if (dist[n][m] == INF) cout << -1 << el;
else cout << dist[n][m] << el;
}
signed main(){
ios::sync_with_stdio(false);cin.tie(nullptr);cout.tie(nullptr);
//freopen("nocross.in", "r", stdin);
//freopen("nocross.out", "w", stdout);
int ntest = 1;
//cin >> ntest;
while (ntest--){
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... |