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>
#define int long long
#define pb push_back
#define mp make_pair
#define all(x) (x).begin(),(x).end()
#define fi first
#define sc second
#define endl "\n"
#define pii pair<int,int>
using namespace std;
const int MAXN = 500+5;
const int mod7 = 1e9+7;
const long long inf = 1e18;
vector<vector<pii>> graf(MAXN);
int n,m;
int calc(char a)
{
if(a == 'E')return 1;
if(a == 'S')return 2;
if(a == 'W')return 3;
if(a == 'N')return 4;
return INT_MAX;
}
int f(char a, char b)
{
int t =(calc(b) - calc(a));
if(t<0)return 4+t;
else return t;
}
set<pii> que;
vector<int> dist(MAXN, inf);
void dikstra(int nod)
{
dist[nod] = 0;
que.insert(mp(0, nod));
while(!que.empty())
{
auto it = que.begin();
int u = it -> second;
que.erase(it);
for(auto x: graf[u])
{
int v = x.fi; int w = x.sc;
if(dist[v] > dist[u]+w)
{
que.erase({dist[v], v});
dist[v] = dist[u] + w;
que.insert({dist[v], v});
}
}
}
}
signed main()
{
ios_base::sync_with_stdio(false),cin.tie(0), cout.tie(0);
int tt=1;
//cin >> tt;
while(tt--)
{
cin >> n >> m;
vector<vector<char>> mat(n, vector<char>(m));
for(int i=0; i<n; i++)
{
string s;cin >> s;
for(int j=0; j<m;j++)
{
mat[i][j] = s[j];
if(calc(s[j]) == INT_MAX)continue;
if(i!=n-1)graf[i*m+j].pb(mp( (i+1)*m+j,f(mat[i][j], 'S')));
if(i!=0)graf[i*m+j].pb(mp((i-1)*m+j,f(mat[i][j], 'N')));
if(j!=0)graf[i*m+j].pb(mp(i*m+j-1,f(mat[i][j], 'W')));
if(j!=m-1)graf[i*m+j].pb(mp(i*m+j+1,f(mat[i][j], 'E')));
}
}
for(int i=0; i<n; i++)
dikstra(0);
if(dist[n*m-1] == inf)cout << -1 << endl;
else cout << dist[n*m-1] << endl;
}
}
# | 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... |