This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
// In the name of Allah
#include <bits/stdc++.h>
using namespace std;
typedef long long int	ll;
typedef long double	ld;
typedef pair<int, int>	pii;
typedef pair<ll, ll>	pll;
#define all(x)		(x).begin(),(x).end()
#define len(x)		((ll) (x).size())
#define F		first
#define S		second
#define pb		push_back
#define sep             ' '
#define endl            '\n'
#define Mp		make_pair
#define kill(x)		cout << x << '\n', exit(0);
#define set_dec(x)	cout << fixed << setprecision(x);
#define file_io(x,y)	freopen(x, "r", stdin); freopen(y, "w", stdout);
int n, m;
const int maxn = 500 + 5;
const ll oo = 8e18;
char a[maxn][maxn];
ll dis[maxn][maxn];
bool mark[maxn][maxn];
priority_queue<pair<ll, pii>> st;
void dij(int x, int y) {
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < m; j++) dis[i][j] = oo;
	}
	dis[x][y] = 0;
	st.push(Mp(-1 * dis[x][y], Mp(x, y)));
	
	while (!st.empty()) {
		auto f = st.top().S;
		st.pop();
		x = f.F, y = f.S;
		if (mark[x][y]) continue;
		mark[x][y] = 1;
		
		if (a[x][y] == 'X') continue;
		
		int d[4] = {0, 0, 0, 0}; // up, right, down, left
		if (a[x][y] == 'N') {
			d[1] = 1; d[2] = 2; d[3] = 3;
		}
		else if (a[x][y] == 'E') {
			d[2] = 1; d[3] = 2; d[0] = 3;
		}
		else if (a[x][y] == 'S') {
			d[3] = 1; d[0] = 2; d[1] = 3;
		}
		else if (a[x][y] == 'W') {
			d[0] = 1; d[1] = 2; d[2] = 3;
		}
		
		for (int T = 0; T < 4; T++) {
			int x1, y1;
			if (T == 0) {
				x1 = x - 1; y1 = y;
			}
			else if (T == 1) {
				x1 = x; y1 = y + 1;
			}
			else if (T == 2) {
				x1 = x + 1; y1 = y;
			}
			else {
				x1 = x; y1 = y - 1;
			}
			
			if (x1 >= 0 && x1 < n && y1 >= 0 && y1 < m) {
				if (dis[x][y] + d[T] < dis[x1][y1]) {
					dis[x1][y1] = dis[x][y] + d[T];
					st.push(Mp(-1 * dis[x1][y1], Mp(x1, y1)));
				}
			}
		}
	}
	
	return ;
}
int main() {
	ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
	
	cin >> n >> m;
	
	for (int i = 0; i < n; i++) {
		string s;
		cin >> s;
		for (int j = 0; j < m; j++) a[i][j] = s[j];
	}
	
	dij(0, 0);
	
	if (dis[n - 1][m - 1] < oo) cout << dis[n - 1][m - 1] << endl;
	else cout << -1 << endl;
	
	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... |