//*** Bismillah ***//
#pragma GCC optimize("O3", "fast-math", "unroll-loops", "no-stack-protector")
#include <bits/stdc++.h>
using namespace std;
#if !defined(ONLINE_JUDGE) and !defined(EVAL)
#include "template/debug.h"
#else
#define d(x...)
#endif
#define fr first
#define er erase
#define sc second
#define in insert
#define ll long long
#define pb push_back
#define vll vector<ll>
#define pll pair<ll,ll>
#define ull unsigned ll
#define vpll vector<pll>
#define len(x) (ll) x.size()
#define all(x) x.begin(),x.end()
const ll INF = 1e9;
const ll INFL = 1e18;
const ll MOD = 1e9+7;
// const ll MOD = 998244353;
const ll maxn = 2e5+5;
ll n,m,k=0;
char a[505][505];
ll dis[505][505];
void _(ll &tt){
cin >> n >> m;
for(ll i = 1; i <= n; i ++){
for(ll j = 1; j <= m; j ++){
cin >> a[i][j];
dis[i][j] = INF;
}
}
auto valid = [&](ll x, ll y) -> bool{
return x >= 1 and x <= n and y >= 1 and y <= m;
};
map<char, char> nxt;
nxt['N'] = 'E';
nxt['E'] = 'S';
nxt['S'] = 'W';
nxt['W'] = 'N';
map<pair<char, char>, ll>memo;
auto get = [&](char a, char b) -> ll{
if(a == b) return 0;
if(memo.count({a, b})) return memo[{a, b}];
ll say = 0;
while(a != b){
a = nxt[a];
say ++;
}
return memo[{a, b}] = say;
};
vector<tuple<ll, ll, char>> v;
v.pb({1, 0, 'S'});
v.pb({-1, 0, 'N'});
v.pb({0, 1, 'E'});
v.pb({0, -1, 'W'});
#define triplet array<ll, 3>
priority_queue<triplet, vector<triplet>, greater<triplet>>q;
dis[1][1] = 0;
q.push({0, 1, 1});
while(!q.empty()){
auto [tmpp, x, y] = q.top();
q.pop();
if(x == n and y == m) continue;
if(dis[x][y] < tmpp) continue;
for(auto [i, j, c] : v){
if(valid(x + i, y + j)){
if(dis[x + i][y + j] > dis[x][y] + get(a[x][y], c)){
dis[x + i][y + j] = dis[x][y] + get(a[x][y], c);
q.push({dis[x + i][y + j], x + i, y + j});
}
}
}
}
cout << dis[n][m] << '\n';
}
signed main() {
ll tm = clock();
cin.tie(0)->sync_with_stdio(0);
ll t = 1;
// cin >> t;
for(ll tt = 1; tt <= t; tt ++) {
_(tt);
}
cerr << "\n\033[1;31mTime: \033[1;30m" \
<< (double)(clock()-tm)/1000000 << "\033[1;32m seconds\n";
}
# | 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... |