#include <bits/stdc++.h>
#define newx x+dx[i]
#define newy y+dy[i]
using namespace std;
struct Coord
{
int x,y;
};
struct comp
{
bool operator()(const pair<int,Coord> &a, const pair<int,Coord> &b) const
{
return a.first > b.first;
}
};
enum {X, N, E, S, W};
const int INF = 9999999;
const int dx[] = {0,-1,0,1,0};
const int dy[] = {0,0,1,0,-1};
int dir[128];
int v[505][505];
int cost[505][505];
priority_queue<pair<int,Coord>, vector<pair<int,Coord>>, comp> pq;
inline int dist(int a, int b)
{
if(a == X) return INF;
return (a <= b ? b-a : b-a+4);
}
signed main()
{
ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
int n,m; cin>>n>>m;
char ch;
dir['N'] = N;
dir['E'] = E;
dir['S'] = S;
dir['W'] = W;
dir['X'] = X;
for(int i=1; i<=n; ++i)
for(int j=1; j<=m; ++j)
{
cin>>ch;
v[i][j] = dir[ch];
cost[i][j] = INF;
}
cost[1][1] = 0;
pq.emplace(0, Coord({1,1}));
while(!pq.empty())
{
int c = pq.top().first;
int x = pq.top().second.x;
int y = pq.top().second.y;
pq.pop();
if(cost[x][y] != c || v[x][y] == X) continue;
for(int i=1; i<=4; ++i)
{
if(cost[newx][newy] > c + dist(v[x][y], i))
{
cost[newx][newy] = c + dist(v[x][y], i);
pq.emplace(cost[newx][newy], Coord({newx, newy}));
}
}
}
cout<<(cost[n][m] == INF ? -1 : cost[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... |