#include <bits/stdc++.h>
using namespace std;
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 oth[505][505];
int dp[505][2];
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];
}
if(n <= 2)
{
dp[1][0] = 0;
dp[1][1] = INF;
for(int i=1; i<m; ++i)
{
dp[i+1][0] = min(dp[i][0], dp[i][1] + dist(v[2][i], N)) + dist(v[1][i], E);
dp[i+1][1] = min(dp[i][1], dp[i][0] + dist(v[1][i], S)) + dist(v[2][i], E);
}
if(n == 1)
{
cout<<(dp[m][0] >= INF ? -1 : dp[m][0]);
}
else
{
int res = min(dp[m][1], dp[m][0] + dist(v[1][m], S));
cout<<(res >= INF ? -1 : res);
}
}
else
{
vector<pair<int,int>> vect = {{1,1},{1,2},{1,3},{2,1},{2,2},{2,3},{3,1},{3,2},{3,3}};
int best = INF;
for(int i=0; i<262144; ++i)
{
int cost = 0, ci = i;
for(auto &j : vect)
{
int x = j.first, y = j.second;
if(v[x][y] == 0)
oth[x][y] = 0;
else
{
cost += dist(v[x][y], (ci & 3) + 1);
oth[x][y] = (ci & 3) + 1;
}
ci >>= 2;
}
int px = 1, py = 1;
while(px != 3 || py != 3)
{
if(oth[px][py] == 0)
{
cost = INF;
break;
}
int val = oth[px][py];
oth[px][py] = 0;
px += dx[val];
py += dy[val];
}
best = min(best, cost);
}
cout<<(best == INF ? -1 : best);
}
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... |