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 pb push_back
#define mp make_pair
#define pii pair<int, ll>
#define fi first
#define se second
void solve() {
int n, m;
cin >> n >> m;
vector<vector<int> > board(1 + n + 1, vector<int> (1 + m + 1, -1));
for(int i = 1; i <= n; ++i) {
for(int j = 1; j <= m; ++j) {
char ch;
cin >> ch;
if(ch == 'N') board[i][j] = 0;
if(ch == 'E') board[i][j] = 3;
if(ch == 'S') board[i][j] = 2;
if(ch == 'W') board[i][j] = 1;
}
}
vector<vector<vector<pair<int, pair<int, int> > > > > graph(1 + n + 1, vector<vector<pair<int, pair<int, int> > > > (1 + m + 1));
for(int i = 1; i <= n; ++i) {
for(int j = 1; j <= m; ++j) {
// cout << i << " " << j << ":\n";
if(board[i][j] == -1) continue;
graph[i][j].pb(mp((board[i][j] + 0) % 4, mp(i - 1, j)));
graph[i][j].pb(mp((board[i][j] + 1) % 4, mp(i, j + 1)));
graph[i][j].pb(mp((board[i][j] + 2) % 4, mp(i + 1, j)));
graph[i][j].pb(mp((board[i][j] + 3) % 4, mp(i, j - 1)));
// for(auto p : graph[i][j]) cout << "{" << p.fi << " {" << p.se.fi << " " << p.se.se << "} }\n";
}
}
vector<vector<bool> > done(1 + n + 1, vector<bool> (1 + m + 1, false));
vector<vector<int> > dist(1 + n + 1, vector<int> (1 + m + 1, 0));
priority_queue<pair<int, pair<int, int> > > q;
q.push(mp(0, mp(1, 1)));
while(!q.empty()) {
auto cur = q.top();
q.pop();
int i = cur.se.fi;
int j = cur.se.se;
int d = -cur.fi;
if(!done[i][j]) {
done[i][j] = true;
dist[i][j] = d;
for(auto nei : graph[i][j]) {
if(!done[nei.se.fi][nei.se.se]) {
q.push(mp(-(d + nei.fi), mp(nei.se.fi, nei.se.se)));
}
}
}
}
if(!done[n][m]) cout << "-1\n";
else cout << dist[n][m] << "\n";
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
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... |