Problem:
一方通行迷路ゲーム
あなたは一方通行迷路ゲームというコンピュータゲームで遊んでいる。このゲームでは、H行W列のマスで区切られた長方形が画面上に表示される。各マスは壁、道、スタート、ゴールのいずれかで、スタートとゴールはそれぞれ一つだけである。道のマスとスタートのマスでは、上下左右に隣接する道のマスかゴールのマスだけに進むことができる。ただし、道のマスのうちいくつかは一方通行のマスであり、上下左右のうち一つの方向にしか出られない。
1回のゲームでは、スタートから出発して道を通ってゴールを目指す。ゴールにたどりつければゲームクリア、たどりつけないことがわかった時点でゲームオーバーである。スタートからゴールまでの移動回数が少ないほど、ランキングが上がる。ゲーム中で一度だけ、一方通行のマスを一つ選んでその方向を好きな方向に変えることができる。ランキング上位を目指すために、あなたは画面をよく見て、どの一方通行のマスを選んで方向を変えればいいか、よく検討しなければならない。
画面上に各マスの情報が与えられたとき、スタートからゴールにたどりつけるかどうか判定し、たどりつけるときは最小の移動回数を報告するプログラムを作成せよ。
入力
入力は以下の形式で与えられる。
$H$ $W$
$s_{1,1}$ $s_{1,2}$ ... $s_{1,W}$
$s_{2,1}$ $s_{2,2}$ ... $s_{2,W}$
:
$s_{H,1}$ $s_{H,2}$ ... $s_{H,W}$
１行目に画面上の長方形の行の数$H$ ($2 \leq H \leq 300$)、列の数$W$ ($2 \leq W \leq 300$)が与えられる。続く$H$行に$i$行$j$列目のマスを表す文字$s_{i,j}$が与えられる。各$s_{i,j}$は以下のどれか一つである。
.
一方通行ではない道
#
壁
U,D,L,R
一方通行の道。それぞれ、上、下、左、右の方向へだけ出られるマスを表す。
S,G
S
がスタート、
G
がゴール。
出力
スタートからゴールにたどりつく最小の移動回数を1行に出力する。ただし、たどりつけないときは「-1」を出力する。
入出力例
入力例１
4 5
##S##
#..##
#.DG.
#..##
出力例１
3
入力例２
4 3
#S.
#U.
GD.
###
出力例２
5
入力例３
3 4
#..#
.LDG
.S#.
出力例３
-1

Submitted solutions:

code_snippet: #include<bits/stdc++.h>
using namespace std;
using ll=long long;
using ul=unsigned long long;
int dx[8] = {1, 0, -1, 0, -1, -1, 1, 1};
int dy[8] = {0, 1, 0, -1, -1, 1, -1, 1};
using Graph=vector<vector<int>>;
ll op(ll a,ll b){return max(a,b);}
ll e(){return -1e18;}
int main(){
    int H,W;
    cin>>H>>W;
    vector<string>S(H);
    for(int i=0;i<H;i++)cin>>S[i];
    string T="DRUL";
    vector<vector<vector<int>>>vis(H,vector<vector<int>>(W,vector<int>(2,-1)));
    queue<tuple<int,int,int>>q;
    int si,sj,gi,gj;
    for(int i=0;i<H;i++){
        for(int j=0;j<W;j++){
            if(S[i][j]=='S')si=i,sj=j;
            if(S[i][j]=='G')gi=i,gj=j;
        }
    }
    q.push({si,sj,0});
    vis[si][sj][0]=0;
    while(!q.empty()){
        auto[i,j,t]=q.front();
        q.pop();
        for(int k=0;k<4;k++){
            int di=i+dx[k],dj=j+dy[k];
            if(di<0||di>=H||dj<0||dj>=W||S[di][dj]=='#'||vis[di][dj][t]!=-1)continue;
            if(S[i][j]=='U'||S[i][j]=='D'||S[i][j]=='R'||S[i][j]=='L'){
                if(T[k]!=S[i][j]){
                    if(t==0){
                        if(vis[di][dj][t+1]!=-1)continue;
                        vis[di][dj][t+1]=vis[i][j][t]+1;
                        q.push({di,dj,t+1});
                        continue;
                    }
                    else continue;
                }
            }
            vis[di][dj][t]=vis[i][j][t]+1;
            q.push({di,dj,t});
        }
    }
    if(vis[gi][gj][0]==-1&&vis[gi][gj][1]==-1)cout<<-1<<endl;
    else if(vis[gi][gj][0]==-1)cout<<vis[gi][gj][1]<<endl;
    else if(vis[gi][gj][1]==-1)cout<<vis[gi][gj][0]<<endl;
    else cout<<min(vis[gi][gj][0],vis[gi][gj][1])<<endl;
}
accuracy: 1
time_ms: 10
memory_kb: 8288
final_rank: 8

code_snippet: #include<bits/stdc++.h>
//#include<atcoder/all>

using namespace std;
//using namespace atcoder;
#define rep(i,n) for(ll i=0; i<n; i++)
#define rrep(i,n) for(ll i=n-1; i>=0; i--)
#define print(a) cout<<a<<endl
typedef long long ll;
#define yn(flg) if(flg){cout<<"Yes"<<endl;}else{cout<<"No"<<endl;}
#define YN(flg) if(flg){cout<<"YES"<<endl;}else{cout<<"NO"<<endl;}
#define so(a) sort(a.begin(),a.end())
#define mp make_pair
#define vi vector<int>
#define vl vector<ll>
#define vs vector<string>
#define pb push_back
#define a2i(a,s) (ll)(a-s)
#define i2a(s,a) (char)(s+a)
#define ssize(a) a.size()
typedef pair<int, int> Pii;
typedef pair<int, ll> Pil;
typedef pair<pair<ll,ll>,ll> P3;
typedef pair<pair<ll,ll>,pair<ll,ll>> P4;

typedef pair<ll, ll> Pll;
typedef pair<ll,Pll> Plll;
typedef pair<Pii, int> Piii;
const ll INF = 1000000000000000000;

template<class T> inline bool chmin(T& a, T b) {
    if (a > b) {
        a = b;
        return true;
    }
    return false;
}
template<class T> inline bool chmax(T& a, T b) {
    if (a < b) {
        a = b;
        return true;
    }
    return false;
}
vector<ll> tate={0,0,1,-1};
vector<ll> yoko={1,-1,0,0};

vector<vector<vector<ll> > > v(310,vector<vector<ll> > (310,vector<ll>(2,INF)));
int main(){
//入力

	cin.tie(0);
	ios::sync_with_stdio(0);

	ll h,w;
	cin>>h>>w;
	Pll S;
	vector<string> s(h);
	rep(i,h){
		cin>>s[i];
		rep(j,w){
			if(s[i][j]=='S')S={i,j};
		}
	}

//判定
	priority_queue<P4,vector<P4>,greater<P4> > que;
	que.push({{0,0},S});
	v[S.first][S.second][0]=0;
	while(!que.empty()){
		ll cost=que.top().first.first,pos=que.top().first.second,x=que.top().second.first,y=que.top().second.second;
		que.pop();
		if(s[x][y]=='#')continue;
		if(s[x][y]=='G'){
			cout<<cost<<endl;
			return 0;
		}
		if(s[x][y]=='U'&&x!=0){
			if(v[x-1][y][pos]==INF){
				que.push({{cost+1,pos},{x-1,y}});
				v[x-1][y][pos]=cost+1;
			}
		}
		if(s[x][y]=='D'&&x!=h-1){
//			cout<<x<<" "<<y<<endl;
			if(v[x+1][y][pos]==INF){
				que.push({{cost+1,pos},{x+1,y}});
				v[x+1][y][pos]=cost+1;
			}
		}
		if(s[x][y]=='L'&&y!=0){
			if(v[x][y-1][pos]==INF){
				que.push({{cost+1,pos},{x,y-1}});
				v[x][y-1][pos]=cost+1;
			}
		}
		if(s[x][y]=='R'&&y!=w-1){
			if(v[x][y+1][pos]==INF){
				que.push({{cost+1,pos},{x,y+1}});
				v[x][y+1][pos]=cost+1;
			}
		}

		for(ll i=0;i<4;i++){
			ll nx=x+tate[i],ny=y+yoko[i];
			if(nx<0||nx>h-1||ny<0||ny>w-1)continue;
			if(s[x][y]=='U'||s[x][y]=='D'||s[x][y]=='L'||s[x][y]=='R'){
				if(pos==0&&v[nx][ny][1]==INF){
					que.push({{cost+1,1},{nx,ny}});
					v[nx][ny][1]=cost+1;
				}
			}else{
				if(v[nx][ny][pos]==INF){
					que.push({{cost+1,pos},{nx,ny}});
					v[nx][ny][pos]=cost+1;
				}
			}
		}
//		cout<<x<<" "<<y<<endl;
	}
//	rep(i,h){
//		rep(j,w){
//			cout<<v[i][j][1]<<" ";
//		}
//		cout<<endl;
//	}

	cout<<-1<<endl;

	return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 8812
final_rank: 13

code_snippet: #include <bits/stdc++.h>
using namespace std;

constexpr int dy[] = {0, 1, 0, -1}, dx[] = {1, 0, -1, 0};

int main(){
    auto st = chrono::steady_clock::now();
    int h, w;
    cin >> h >> w;
    vector<string> S(h);
    for(auto &i : S) cin >> i;
    
    int sy{}, sx{};
    for(int i = 0; i < h*w; i++){
        if(S[i/w][i%w] == 'S'){
            sy = i/w; sx = i%w;
            break;
        }
    }
    
    vector<vector<vector<int>>> dist(2, vector<vector<int>>(h, vector<int>(w, -1)));
    dist[0][sy][sx] = 0;
    queue<array<int, 3>> Q;
    Q.push({0, sy, sx});
    
    while(!Q.empty()){
        int p = Q.front()[0], y = Q.front()[1], x = Q.front()[2];
        Q.pop();
        int d = dist[p][y][x];
        
        int nc = S[y][x];
        if(nc != '.' && nc != 'S'){
            int ny = y, nx = x;
            if(nc == 'R') nx = x+1;
            else if(nc == 'D') ny = y+1;
            else if(nc == 'L') nx = x-1;
            else if(nc == 'U') ny = y-1;
            
            if(ny >= 0 && nx >= 0 && ny < h && nx < w && S[ny][nx] != '#' && dist[p][ny][nx] == -1){
                dist[p][ny][nx] = d+1;
                Q.push({p, ny, nx});
            }
            
            if(p == 1) continue;
            p = 1;
        }
        
        for(int t = 0; t < 4; t++){
            int ny = y+dy[t], nx = x+dx[t];
            if((ny|nx) < 0 || ny >= h || nx >= w) continue;
            char c = S[ny][nx];
            if(c == '#') continue;
            if(c == 'G'){
                cout << d+1 << '\n';
                return 0;
            } else {
                if(dist[p][ny][nx] != -1) continue;
                dist[p][ny][nx] = d + 1;
                Q.push({p, ny, nx});
            }
        }
    }
    
    while(chrono::duration_cast<chrono::milliseconds>(chrono::steady_clock::now()-st).count() < 100);
    cout << -1 << '\n';
}
accuracy: 0.14285714285714285
time_ms: 100
memory_kb: 3348
final_rank: 20

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
vector<ll> mx={0,1,0,-1},my={1,0,-1,0};
vector<vector<ll>> ch;

void dfs(vector<vector<char>> &m,pair<ll,ll> now,ll cnt,bool can){
    ch[now.first][now.second]=cnt;
    if(m[now.first][now.second]=='U'){
        if(m[now.first+mx[3]][now.second+my[3]]!='#'&&(ch[now.first+mx[3]][now.second+my[3]]==-1||ch[now.first+mx[3]][now.second+my[3]]>cnt+1)){
            dfs(m,{now.first+mx[3],now.second+my[3]},cnt+1,can);
        }
        if(can){
            can=false;
            for(ll i=0;i<4;i++){
                if(m[now.first+mx[i]][now.second+my[i]]!='#'&&(ch[now.first+mx[i]][now.second+my[i]]==-1||ch[now.first+mx[i]][now.second+my[i]]>cnt+1)){
                    dfs(m,{now.first+mx[i],now.second+my[i]},cnt+1,can);
                }
            }
            can=true;
        }
    }else if(m[now.first][now.second]=='D'){
        if(m[now.first+mx[1]][now.second+my[1]]!='#'&&(ch[now.first+mx[1]][now.second+my[1]]==-1||ch[now.first+mx[1]][now.second+my[1]]>cnt+1)){
            dfs(m,{now.first+mx[1],now.second+my[1]},cnt+1,can);
        }
        if(can){
            can=false;
            for(ll i=0;i<4;i++){
                if(m[now.first+mx[i]][now.second+my[i]]!='#'&&(ch[now.first+mx[i]][now.second+my[i]]==-1||ch[now.first+mx[i]][now.second+my[i]]>cnt+1)){
                    dfs(m,{now.first+mx[i],now.second+my[i]},cnt+1,can);
                }
            }
            can=true;
        }
    }else if(m[now.first][now.second]=='L'){
        if(m[now.first+mx[2]][now.second+my[2]]!='#'&&(ch[now.first+mx[2]][now.second+my[2]]==-1||ch[now.first+mx[2]][now.second+my[2]]>cnt+1)){
            dfs(m,{now.first+mx[2],now.second+my[2]},cnt+1,can);
        }
        if(can){
            can=false;
            for(ll i=0;i<4;i++){
                if(m[now.first+mx[i]][now.second+my[i]]!='#'&&(ch[now.first+mx[i]][now.second+my[i]]==-1||ch[now.first+mx[i]][now.second+my[i]]>cnt+1)){
                    dfs(m,{now.first+mx[i],now.second+my[i]},cnt+1,can);
                }
            }
            can=true;
        }
    }else if(m[now.first][now.second]=='R'){
        if(m[now.first+mx[0]][now.second+my[0]]!='#'&&(ch[now.first+mx[0]][now.second+my[0]]==-1||ch[now.first+mx[0]][now.second+my[0]]>cnt+1)){
            dfs(m,{now.first+mx[0],now.second+my[0]},cnt+1,can);
        }
        if(can){
            can=false;
            for(ll i=0;i<4;i++){
                if(m[now.first+mx[i]][now.second+my[i]]!='#'&&(ch[now.first+mx[i]][now.second+my[i]]==-1||ch[now.first+mx[i]][now.second+my[i]]>cnt+1)){
                    dfs(m,{now.first+mx[i],now.second+my[i]},cnt+1,can);
                }
            }
            can=true;
        }
    }else{
        for(ll i=0;i<4;i++){
            if(m[now.first+mx[i]][now.second+my[i]]!='#'&&(ch[now.first+mx[i]][now.second+my[i]]==-1||ch[now.first+mx[i]][now.second+my[i]]>cnt+1)){
                dfs(m,{now.first+mx[i],now.second+my[i]},cnt+1,can);
            }
        }
    }
}

int main() {
    ll h,w;cin >> h >> w;
    vector<vector<char>> m(h+2,vector<char>(w+2,'#'));
    pair<ll,ll> s,g;
    for(ll i=0;i<h;i++){
        for(ll j=0;j<w;j++){
            cin >> m[i+1][j+1];
            if(m[i+1][j+1]=='S'){
                s={i+1,j+1};
            }else if(m[i+1][j+1]=='G'){
                g={i+1,j+1};
            }
        }
    }
    ch.resize(h+2,vector<ll>(w+2,-1));
    dfs(m,s,0,true);
    cout << ch[g.first][g.second] << endl;
}
accuracy: 0.35714285714285715
time_ms: 60
memory_kb: 3832
final_rank: 19

code_snippet: #include <iostream>
#include <vector>
#include <string>
#include <queue>
#include <tuple>
#include <algorithm>
using namespace std;
const int INF = 1e9;
int main() {
    int H, W;
    cin >> H >> W;
    vector<string> m(H);
    int sy, sx, gy, gx;
    for (int i = 0; i < H; ++i) {
        cin >> m[i];
        for (int j = 0; j < W; ++j) {
            if (m[i][j] == 'S') {
                sy = i;
                sx = j;
            }
            if (m[i][j] == 'G') {
                gy = i;
                gx = j;
            }
        }
    }
    vector<vector<vector<int>>> d(H, vector<vector<int>>(W, vector<int>(2, -1)));
    queue<tuple<int, int, int>> q;
    d[sy][sx][0] = 0;
    q.push({sy, sx, 0});
    int dy[] = {0, 1, 0, -1};
    int dx[] = {1, 0, -1, 0};
    string dc = "RDLU";
    while (!q.empty()) {
        auto [y, x, k] = q.front();
        q.pop();
        int c = d[y][x][k];
        for (int i = 0; i < 4; ++i) {
            char ch = m[y][x];
            if (ch == 'U' || ch == 'D' || ch == 'L' || ch == 'R') {
                if (ch != dc[i]) continue;
            }
            int ny = y + dy[i];
            int nx = x + dx[i];
            if (ny < 0 || ny >= H || nx < 0 || nx >= W || m[ny][nx] == '#') continue;
            if (d[ny][nx][k] != -1) continue;
            d[ny][nx][k] = c + 1;
            q.push({ny, nx, k});
        }
        if (k == 0) {
            char ch = m[y][x];
            if (ch == 'U' || ch == 'D' || ch == 'L' || ch == 'R') {
                for (int i = 0; i < 4; ++i) {
                    int ny = y + dy[i];
                    int nx = x + dx[i];
                    if (ny < 0 || ny >= H || nx < 0 || nx >= W || m[ny][nx] == '#') continue;
                    if (d[ny][nx][1] != -1) continue;
                    d[ny][nx][1] = c + 1;
                    q.push({ny, nx, 1});
                }
            }
        }
    }

    int ans = INF;
    if (d[gy][gx][0] != -1) ans = min(ans, d[gy][gx][0]);
    if (d[gy][gx][1] != -1) ans = min(ans, d[gy][gx][1]);
    if (ans == INF) cout << -1 << endl;
    else cout << ans << endl;
    return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 8288
final_rank: 8

code_snippet: # include <algorithm>
# include <bitset>
# include <complex>
# include <cmath>
#define _USE_MATH_DEFINES
#include <assert.h>
# include <math.h>
# include <deque>
# include <exception>
# include <fstream>
# include <functional>
# include <iomanip>
# include <ios>
# include <iosfwd>
# include <iostream>
# include <istream>
# include <iterator>
# include <limits>
# include <list>
# include <locale>
# include <map>
# include <memory>
# include <new>
# include <numeric>
# include <ostream>
# include <queue>
# include <set>
# include <sstream>
# include <stack>
# include <stdexcept>
# include <streambuf>
# include <string>
# include <typeinfo>
# include <utility>
# include <valarray>
# include <vector>
# include <array>
# include <atomic>
# include <chrono>
# include <condition_variable>
# include <forward_list>
# include <future>
# include <initializer_list>
# include <mutex>
# include <random>
# include <ratio>
# include <regex>
# include <scoped_allocator>
# include <system_error>
# include <thread>
# include <tuple>
# include <typeindex>
# include <type_traits>
# include <unordered_map>
# include <unordered_set>
# include <bitset>
#pragma GCC target ("avx")
#pragma GCC optimize("O3")
#pragma GCC optimize("unroll-loops")
#define rep(i,n) for (ll i = 0;i < (ll)(n);i++)
#define Yes cout << "Yes" << "\n"// YESの短縮
#define No cout << "No" << "\n"// NOの短縮
#define rtr0 return(0)//return(0)の短縮
#define gyakugen(x) modpow(x,mod - 2,mod);
#define agyakugen(x) modpow(x,amod - 2,amod);
#define st(A) sort(A.begin(),A.end());
#define rst(A) sort(A.rbegin(),A.rend());
#define rev(A) reverse(A.begin(),A.end());
using namespace std;
//using namespace ranges;
using ll = long long;//63bit型整数型
using ld = long double;//doubleよりも長い値を保存できるもの
using ull = unsigned long long;//符号がない64bit型整数
//ld m_pi = 3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679;
ll mod = 998244353;
ll amod = 1000000007;
ll MINF = -5000000000000000000;
ll INF = 5000000000000000000;
ll inf = 2000000000;
ll minf = -2000000000;
ll BAD = -1;
ll zero = 0;
ld EPS = 1e-10;
vector<ll>randomhash = {(ll)1e9 + 7,(ll)1e9 + 801,((ll)1e8 * 8) + 29,((ll)1e8 * 7) + 159,((ll)1e8 * 9) + 221};
vector<ll>tate = {0,-1,0,1};//グリッド上の全探索時の四方向の上下のチェック
vector<ll>yoko = {1,0,-1,0};//グリッド上の全探索時の四方向の右左のチェック
vector<ll>etate = {0,-1,-1,-1,0,1,1,1};//グリッド上の全探索時の八方向の上下のチェック
vector<ll>eyoko = {1,1,0,-1,-1,-1,0,1};//グリッド上の全探索時の八方向の右左のチェック
vector<ll>hexsax = {0,1,1,0,-1,-1};
vector<ll>hexsay = {1,1,0,-1,-1,0};
//返り値は素数のリスト。
vector < bool > isprime;
vector < ll > Era(int n){//書き方 vector<ll>[] = Era(x); とやるとxまでの素数が出てくる。
	isprime.resize(n, true);
	vector < ll > res;
	isprime[0] = false;
	isprime[1] = false;
	for(ll i = 2; i < n; ++i) isprime[i] = true;
	for(ll i = 2; i < n; ++i) {
		if(isprime[i]) {
			res.push_back(i);
			for(ll j = i * 2; j < n; j += i) isprime[j] = false;
		}
	}
	return res;
}
ll ceil_div(ll a, ll b){
    if (b <= 0) return INF; // invalid (分母<=0 のときは不可能と扱う)
    return (a + b - 1) / b;
}
//　　　　　　素数判定 21~35
ull modmul(ull a,ull b,ull mod) {
    return (ull)a*b%mod;
}
ll modpow(ll a, ll n, ll mod) {
	ll res = 1;
	while (n > 0) {
		if (n & 1) res = res * a % mod;
		a = a * a % mod;
		n >>= 1;
	}
	return res;
}

long long npow(long long a, long long n){
    long long res = 1;
    while (n > 0) {
		if (n & 1) res = res * a;
		a = a * a;
		n >>= 1;
	}
	return res;
}
//     モッドを使った累乗
long long isqrt(long long num){
    return((long long)sqrtl(num));
}
ld get_theta(ld px,ld py,ld fx,ld fy,ld sx,ld sy){
    ld fxv = fx-px;
    ld fyv = fy-py;
    ld sxv = sx-px;
    ld syv = sy-py;
    ld fsv = fxv*sxv + fyv*syv;
    ld pfs = (ld)sqrt(fxv*fxv+fyv*fyv);
    ld pss = (ld)sqrt(sxv*sxv+syv*syv);
    return acos(fsv/(pfs*pss))*180/M_PI;
};
ld Euclidean_distance(ll x1,ll y1,ll x2,ll y2){
    ld x = abs((ld)x1 - (ld)x2);
    ld y = abs((ld)y1 - (ld)y2);
    return sqrt((x*x) + (y*y));
};
ll Manhattan_distance(ll x1,ll y1,ll x2,ll y2){
    return abs(x1-x2)+abs(y1-y2);
};
void change_bit(ll N,ll start,vector<ll>&X){
    for(ll i = start;i>=0;i--){
        ll a = npow(2,i);
        if(N/a==1){
            X[i]=1;
            N-=a;
        }
    }
}
ll popcount(ll x) {
    int count = 0;
    while (x) {
        count += x & 1;
        x >>= 1;
    }
    return count;
}

ll cutup(ll a,ll b){
    return (a+b-1)/b;
}
void Run_Length_Encoding(vector<ll>A,vector<pair<ll,ll>>&RLE){
    RLE.push_back({A[0],1});
    ll N = A.size();
    for(int i = 1;i<N;i++){
        if(RLE[RLE.size()-1].first==A[i])RLE[RLE.size()-1].second++;
        else RLE.push_back({A[i],1});
    }
}
bool is_in_grid(ll i,ll ii,ll H,ll W){
    bool res = false;
    if(i>=0&&i<H&&ii>=0&&ii<W)res=true;
    return res;
}
template<class T>
struct rolling_hash{
    vector<ull>Power,hash,InvPower;
    ll B = 0;
    ll MOD = 0;
    void set_number(ll base,ll mod){
        B = base;
        MOD = mod;
    }
    void do_hash(const T &S) {
        ll N = S.size();
        Power.resize(N+1);
        InvPower.resize(N+1);
        hash.resize(N+1);
        Power[0] = 1;
        InvPower[0] = 1;
        for (ll i = 0;i<N;i++) {
            Power[i + 1] = modmul(Power[i],B,MOD);
            InvPower[i + 1] = modpow(Power[i+1],MOD-2,MOD);
            hash[i + 1] = (hash[i] + modmul(S[i], Power[i],MOD))%MOD;
        }
    }
    ll get_hash(ll l, ll r) {
        ull res = (hash[r]+MOD-hash[l])%MOD;
        res = modmul(res,InvPower[l],MOD);
        return res;
    }
};
template<class T>
struct combination{
  public:
    vector<T>factorial;
    ll MOD;
    ll N;
    void reset(T n,T mod){
        N = n+1;
        factorial.assign(N,1);
        MOD = mod;
    }
    void calu(){
        for(ll i = 1;i<N;i++){
            factorial[i] = (factorial[i-1]*(i))%MOD;
        }
    }
    T get(T n, T r){
        ll a = factorial[n];
        ll b = (factorial[r]*(factorial[n-r]))%MOD;
        b = modpow(b,MOD - 2,MOD);
        return (a*b)%MOD;
    }
};
template<class T>
struct dijkstra{
  public:
	vector<vector<pair<T,T>>>graph;
	vector<T>ans;
	priority_queue<pair<T,T>,vector<pair<T,T>>,greater<pair<T,T>>>pq;
    void do_dijkstra(T start){//頂点xからダイクストラを行う
		pq.push({0,start});
		ans[start] = 0;
		while(true){
			if(pq.empty())break;
			T cost = pq.top().first;
			T vertex = pq.top().second;
			pq.pop();
            if (cost > ans[vertex]) continue; 
			for(T i = 0;i<graph[vertex].size();i++){
				T nextvertex = graph[vertex][i].first;
				T nextcost = graph[vertex][i].second + cost;
				if(ans[nextvertex] <= nextcost)continue;
					ans[nextvertex] = nextcost;
					pq.push({nextcost,nextvertex});
			}
		}
	}
	void make_indirectedgraph(T u,T v,T cost){//無向辺のグラフ作成
		graph[u].push_back({v,cost});
		graph[v].push_back({u,cost});
	}
	void make_directedgraph(T u,T v,T cost){//有向辺のグラフ作成
		graph[u].push_back({v,cost});
	}
	T output(T end){//答えを出す
		return ans[end];
	} 
	void reset(T N){//リセット
		graph.assign(N, {});
        ans.assign(N, INF);
	}
};
template<class T>
struct unionfind {
public:
    vector<T> parent, rank;
    void reset(T N) { // 初期化
        parent.resize(N);
        rank.assign(N, 1); // 各集合のサイズを 1 にする
        for (T i = 0; i < N; i++) parent[i] = i;
    }
    T leader(T x) { // 経路圧縮による親の取得
        if (parent[x] == x) return x;
        return parent[x] = leader(parent[x]); // 経路圧縮
    }
    void marge(T x, T y) { // ランクによるマージ
        T a = leader(x), b = leader(y);
        if(a!=b){
            if (rank[a] < rank[b]) swap(a, b);
            parent[b] = a;
            rank[a] += rank[b]; // サイズを更新    
        }
    }
    bool same(T x, T y) { // 同じ集合か判定
        return leader(x) == leader(y);
    }
    T size(T x) { // 集合のサイズを取得
        return rank[leader(x)];
    }
    void check(T N) { // デバッグ用: 親の確認
        for (T i = 0; i < N; i++) cout << parent[i] << " ";
        cout << "\n";
    }
};
//セグ木
template <class S, S (*op)(S, S), S (*e)()> struct segtree {
    public:
        segtree() : segtree(0) {}
        segtree(int n) : segtree(std::vector<S>(n, e())) {}
        segtree(const std::vector<S>& v) : _n(int(v.size())){
            log = ceil_pow2(_n);
            size = 1 << log;
            d = std::vector<S>(2 * size, e());
            for (int i = 0; i < _n; i++) d[size + i] = v[i];
            for (int i = size - 1; i >= 1; i--) {
                update(i);
            }
        }
  
        void set(int p, S x) {
            assert(0 <= p && p < _n);
            p += size;
            d[p] = x;
            for (int i = 1; i <= log; i++) update(p >> i);
        }
  
        S get(int p) {
            assert(0 <= p && p < _n);
            return d[p + size];
        }
  
        S prod(int l, int r) {
            assert(0 <= l && l <= r && r <= _n);
            S sml = e(), smr = e();
            l += size;
            r += size;
  
            while (l < r) {
                if (l & 1) sml = op(sml, d[l++]);
                if (r & 1) smr = op(d[--r], smr);
                l >>= 1;
                r >>= 1;
            }
            return op(sml, smr);
        }
  
        S all_prod() { return d[1]; }
  
        template <bool (*f)(S)> int max_right(int l) {
            return max_right(l, [](S x) { return f(x); });
        }
        template <class F> int max_right(int l, F f) {
            assert(0 <= l && l <= _n);
            assert(f(e()));
            if (l == _n) return _n;
            l += size;
            S sm = e();
            do{
                while (l % 2 == 0) l >>= 1;
                if (!f(op(sm, d[l]))) {
                    while (l < size) {
                        l = (2 * l);
                        if (f(op(sm, d[l]))) {
                            sm = op(sm, d[l]);
                            l++;
                        }
                    }
                    return l - size;
                }
                sm = op(sm, d[l]);
                l++;
            }while ((l & -l) != l);
            return _n;
        }
  
        template <bool (*f)(S)> int min_left(int r) {
            return min_left(r, [](S x) { return f(x); });
        }
        template <class F> int min_left(int r, F f) {
            assert(0 <= r && r <= _n);
            assert(f(e()));
            if (r == 0) return 0;
            r += size;
            S sm = e();
            do{
                r--;
                while (r > 1 && (r % 2)) r >>= 1;
                if (!f(op(d[r], sm))) {
                    while (r < size) {
                        r = (2 * r + 1);
                        if (f(op(d[r], sm))) {
                            sm = op(d[r], sm);
                            r--;
                        }
                    }
                    return r + 1 - size;
                }
                sm = op(d[r], sm);
            }while ((r & -r) != r);
            return 0;
        }
  
    private:
        int _n, size, log;
        std::vector<S> d;
  
        void update(int k) { d[k] = op(d[2 * k], d[2 * k + 1]); }
        int ceil_pow2(int n) {
            int x = 0;
            while ((1U << x) < (unsigned int)(n)) x++;
            return x;
        }
};

//遅延セグ木
template <class S,S (*op)(S, S),S (*e)(),class F,S (*mapping)(F, S),F (*composition)(F, F),F (*id)()>
struct lazy_segtree {

    public:
        lazy_segtree() : lazy_segtree(0) {}
        lazy_segtree(int n) : lazy_segtree(std::vector<S>(n, e())) {}
        lazy_segtree(const std::vector<S>& v) : _n(int(v.size())) {
            log = ceil_pow2(_n);
            size = 1 << log;
            d = std::vector<S>(2 * size, e());
            lz = std::vector<F>(size, id());
            for (int i = 0; i < _n; i++) d[size + i] = v[i];
            for (int i = size - 1; i >= 1; i--) {
                update(i);
            }
        }

    void set(int p, S x) {
        assert(0 <= p && p < _n);
        p += size;
        for (int i = log; i >= 1; i--) push(p >> i);
        d[p] = x;
        for (int i = 1; i <= log; i++) update(p >> i);
    }

    S get(int p) {
        assert(0 <= p && p < _n);
        p += size;
        for (int i = log; i >= 1; i--) push(p >> i);
        return d[p];
    }

    S prod(int l, int r) {
        assert(0 <= l && l <= r && r <= _n);
        if (l == r) return e();

        l += size;
        r += size;

        for (int i = log; i >= 1; i--) {
            if (((l >> i) << i) != l) push(l >> i);
            if (((r >> i) << i) != r) push(r >> i);
        }

        S sml = e(), smr = e();
        while (l < r) {
            if (l & 1) sml = op(sml, d[l++]);
            if (r & 1) smr = op(d[--r], smr);
            l >>= 1;
            r >>= 1;
        }

        return op(sml, smr);
    }

    S all_prod() { return d[1]; }

    void apply(int p, F f) {
        assert(0 <= p && p < _n);
        p += size;
        for (int i = log; i >= 1; i--) push(p >> i);
        d[p] = mapping(f, d[p]);
        for (int i = 1; i <= log; i++) update(p >> i);
    }
    void apply(int l, int r, F f) {
        assert(0 <= l && l <= r && r <= _n);
        if (l == r) return;

        l += size;
        r += size;

        for (int i = log; i >= 1; i--) {
            if (((l >> i) << i) != l) push(l >> i);
            if (((r >> i) << i) != r) push((r - 1) >> i);
        }

        {
            int l2 = l, r2 = r;
            while (l < r) {
                if (l & 1) all_apply(l++, f);
                if (r & 1) all_apply(--r, f);
                l >>= 1;
                r >>= 1;
            }
            l = l2;
            r = r2;
        }

        for (int i = 1; i <= log; i++) {
            if (((l >> i) << i) != l) update(l >> i);
            if (((r >> i) << i) != r) update((r - 1) >> i);
        }
    }

    template <bool (*g)(S)> int max_right(int l) {
        return max_right(l, [](S x) { return g(x); });
    }
    template <class G> int max_right(int l, G g) {
        assert(0 <= l && l <= _n);
        assert(g(e()));
        if (l == _n) return _n;
        l += size;
        for (int i = log; i >= 1; i--) push(l >> i);
        S sm = e();
        do {
            while (l % 2 == 0) l >>= 1;
            if (!g(op(sm, d[l]))) {
                while (l < size) {
                    push(l);
                    l = (2 * l);
                    if (g(op(sm, d[l]))) {
                        sm = op(sm, d[l]);
                        l++;
                    }
                }
                return l - size;
            }
            sm = op(sm, d[l]);
            l++;
        } while ((l & -l) != l);
        return _n;
    }

    template <bool (*g)(S)> int min_left(int r) {
        return min_left(r, [](S x) { return g(x); });
    }
    template <class G> int min_left(int r, G g) {
        assert(0 <= r && r <= _n);
        assert(g(e()));
        if (r == 0) return 0;
        r += size;
        for (int i = log; i >= 1; i--) push((r - 1) >> i);
        S sm = e();
        do {
            r--;
            while (r > 1 && (r % 2)) r >>= 1;
            if (!g(op(d[r], sm))) {
                while (r < size) {
                    push(r);
                    r = (2 * r + 1);
                    if (g(op(d[r], sm))) {
                        sm = op(d[r], sm);
                        r--;
                    }
                }
                return r + 1 - size;
            }
            sm = op(d[r], sm);
        } while ((r & -r) != r);
        return 0;
    }

    private:
        int _n, size, log;
        std::vector<S> d;
        std::vector<F> lz;
        int ceil_pow2(int n) {
            int x = 0;
            while ((1U << x) < (unsigned int)(n)) x++;
            return x;
        }
        void update(int k) { d[k] = op(d[2 * k], d[2 * k + 1]); }
        void all_apply(int k, F f) {
            d[k] = mapping(f, d[k]);
            if (k < size) lz[k] = composition(f, lz[k]);
        }
        void push(int k) {
            all_apply(2 * k, lz[k]);
            all_apply(2 * k + 1, lz[k]);
            lz[k] = id();
        }
};
struct Euler_Tour{//最小共通祖先,部分木のコスト,通り道のコスト,のグラフを作る部分(オイラーツアー)
    //必要なもの集
    //セグ木は2*Nがベース
    //LCA(最小共通祖先)discovery,finish,visit,high
    //とある頂点xを根とする部分木の範囲 discovery,finish
    //頂点xを根とする部分木の辺と頂点のコストの総和 discovery,finish,vcost1,ecost1
    //頂点xを根とする頂点yまでの最短の辺と頂点のコストの総和 discovery,finish,vcost2,ecost2
    vector<int>discovery,finish,visit,high,vweight,vcost1,vcost2,ecost1,ecost2;
    vector<int>other;
    vector<vector<pair<int,int>>>graph;
    int cnt;
    int othercnt;
    void reset(ll N){
        cnt = 0;
        othercnt = 0;
        other.assign(2*N,0);
        discovery.assign(N,inf);
        finish.assign(N,minf);
        vweight.assign(N,0);
        graph.assign(N,vector<pair<int,int>>(0));
        visit.assign(2*N,0);
        high.assign(2*N,0);
        vcost1.assign(2*N,0);
        vcost2.assign(2*N,0);
        ecost1.assign(2*N,0);
        ecost2.assign(2*N,0);
    };
    void make_graph(ll u,ll v,ll cost){
        if(max(u,v)>graph.size()){
            cout << "not reset or out of range" << "\n";
            return;
        }
        graph[u].push_back({v,cost});
        graph[v].push_back({u,cost});
    }
    void set_vweight(ll vertex,ll cost){
        vweight[vertex]+=cost;
    }
    void DFS(ll vertex,ll nowdepth,ll cost){
        if(discovery[vertex]==inf){
            vcost1[cnt]=vweight[vertex];
            vcost2[cnt]=vweight[vertex];
        }
        else{
            vcost1[cnt]=0;
            vcost2[cnt]=0;
        }
        ecost1[cnt]=cost;
        ecost2[cnt]=cost;
        discovery[vertex]=min(discovery[vertex],cnt);
        visit[cnt]=vertex;
        high[cnt]=nowdepth;
        for(int i = 0;i<graph[vertex].size();i++){
            int x = graph[vertex][i].first;
            int nextcost = graph[vertex][i].second;
            if(discovery[x]!=inf&&graph[vertex].size()==1)othercnt++;
            other[cnt]=othercnt;
            if(discovery[x]==inf){
                cnt++;
                DFS(x,nowdepth+1,nextcost);
                cnt++;
                visit[cnt]=vertex;
                high[cnt]=nowdepth;
                vcost1[cnt]=0;
                ecost1[cnt]=0;
                vcost2[cnt]=vweight[x]*-1;
                ecost2[cnt]=nextcost*-1;
            }
            other[cnt]=othercnt;
        }
        finish[vertex]=cnt+1;
        return;
    }
    int get_size(){
        ll res = high.size()-1;
        return res;
    }
    int get_vcost1(ll i){
        return ecost1[i];
    }
    int get_vcost2(ll i){
        return vcost2[i];
    }
    int get_ecost1(ll i){
        return vcost1[i];
    }
    int get_ecost2(ll i){
        return ecost2[i];
    }
    int get_high(ll i){
        return high[i];
    }
    int get_visit(ll i){
        return visit[i];
    }
    int get_discovery(ll i){
        return discovery[i];
    }
    int get_finish(ll i){
        return finish[i];
    }
};
//遅延セグ木のベース
//型
using segS = ll;
segS oop(segS a,segS b){
    return (a+b)%mod;
}
segS ee(){
    return 0;
}
/*struct segS{
    ll mi = 0;
    ll ma = 0;
};
segS oop(segS a,segS b){
    segS res;
    res.mi = min(a.mi,b.mi);
    res.ma = max(a.ma,b.ma);
    return res;
}
segS ee(){
    segS res;
    res.mi = INF;
    res.ma = MINF;
    return res;
}*/

//using lazyS = ll;
using lazyS = ll;
using lazyF = ll;
lazyS e(){
    lazyS res;
    res = 1;
    return res;
}//範囲外などを起こしてしまったときの返り値
lazyS op(lazyS a, lazyS b){
    lazyS res;
    res = a+b;
    return res; 
}//操作したいこと
lazyS mapping(lazyF f, lazyS x){ 
    x= (x*f)%mod;
    return x; 
}//下まで伝播させたいこと
lazyF composition(lazyF f, lazyF g){ return g = (g*f)%mod; }//まとめてやった場合おこしたいこと
lazyF id(){ return 1; }//遅延セグ木のベース
/*
using lazyS = ll;
using lazyF = ll;
lazyS e(){ return 0;}//範囲外などを起こしてしまったときの返り値
lazyS op(lazyS a, lazyS b){ return a+b; }//操作したいこと
lazyS mapping(lazyF f, lazyS x){ return x /= f; }//下まで伝播させたいこと
lazyF composition(lazyF f, lazyF g){ return g /= f; }//まとめてやった場合おこしたいこと
lazyF id(){ return 1; }//遅延セグ木のベース
*/

int main(){
ll H,W;
cin >> H >> W;
vector<string>grid(H);
vector<vector<vector<ll>>>ans(2,vector<vector<ll>>(H,vector<ll>(W,INF)));
vector<vector<vector<bool>>>visited(2,vector<vector<bool>>(H,vector<bool>(W)));
ll sx,sy,ex,ey;
for(int i = 0;i<H;i++){
    cin >> grid[i];
    for(int ii = 0;ii<W;ii++){
        if(grid[i][ii]=='S'){
            sx = i;
            sy = ii;
        }
        if(grid[i][ii]=='G'){
            ex = i;
            ey = ii;
        }
    }
}
priority_queue<tuple<ll,ll,ll,ll>,vector<tuple<ll,ll,ll,ll>>,greater<tuple<ll,ll,ll,ll>>>pq;
pq.emplace(0,0,sx,sy);
ans[0][sx][sy] = 0; 
while(true){
    if(pq.empty())break;
    auto[dimension,cnt,x,y] = pq.top();
    pq.pop();
    if(cnt>ans[dimension][x][y])continue;
    if(grid[x][y]=='.'){
        for(int i = 0;i<4;i++){
            ll X = x+tate[i];
            ll Y = y+yoko[i];
            if(!is_in_grid(X,Y,H,W))continue;
            if(grid[X][Y]=='#')continue;
            if(ans[dimension][X][Y]<=cnt+1)continue;
            ans[dimension][X][Y] = cnt+1;
            pq.emplace(dimension,cnt+1,X,Y);
        }
    }
    else{
        for(int i = 0;i<4;i++){
            ll X = x+tate[i];
            ll Y = y+yoko[i];
            ll ndimension = dimension;
            if(!is_in_grid(X,Y,H,W))continue;
            if(grid[X][Y]=='#')continue;
            if(grid[x][y]=='R')if(i!=0)ndimension++;
            if(grid[x][y]=='U')if(i!=1)ndimension++;
            if(grid[x][y]=='L')if(i!=2)ndimension++;
            if(grid[x][y]=='D')if(i!=3)ndimension++;
            if(ndimension==2)continue;
            if(ans[ndimension][X][Y]<=cnt+1)continue;
            ans[ndimension][X][Y] = cnt+1;
            pq.emplace(ndimension,cnt+1,X,Y);
        }
    }
}
//cout << ans[0][ex][ey] << "\n";
cout << (min(ans[0][ex][ey],ans[1][ex][ey]) == INF ? -1:min(ans[0][ex][ey],ans[1][ex][ey])) << "\n";
}
accuracy: 1
time_ms: 30
memory_kb: 10728
final_rank: 17

code_snippet: #include<algorithm>
#include<iostream>
#include<cmath>
#include<cstdio>
#include<iomanip>
#include<utility>
#include<string>
#include<vector>
#include<bit>
#include<bitset>
#include<tuple>
#include<map>
#include<set>
#include<queue>
#include<deque>
#include<stack>
using namespace std;

void fix(int x){
  cout << fixed << setprecision(x);
}

int main(){
  long int H, W, X, Y, GX, GY;
  cin >> H >> W;
  vector<string> A(H);
  for (long int i = 0; i < H; i++){
    cin >> A.at(i);
    for (long int j = 0; j < W; j++){
      if (A.at(i).at(j) == 'S'){
        Y = i;
        X = j;
      }
      if (A.at(i).at(j) == 'G'){
        GY = i;
        GX = j;
      }
    }
  }
  vector<vector<long int> > B(H, vector<long int>(W, 100000000));
  vector<vector<long int> > C(H, vector<long int>(W, 100000000));
  queue<pair<long int, long int> > Q;
  Q.push(make_pair(Y, X));
  B.at(Y).at(X) = 0;
  while (!Q.empty()){
    Y = Q.front().first;
    X = Q.front().second;
    Q.pop();
    if (A.at(Y).at(X) == '.' || A.at(Y).at(X) == 'S'){
      if (Y != 0){
        if (A.at(Y - 1).at(X) != '#'){
          if (B.at(Y - 1).at(X) == 100000000 && B.at(Y).at(X) != 100000000 && C.at(Y - 1).at(X) == 100000000 && C.at(Y).at(X) != 100000000){
            B.at(Y - 1).at(X) = B.at(Y).at(X) + 1;
            C.at(Y - 1).at(X) = C.at(Y).at(X) + 1;
            Q.push(make_pair(Y - 1, X));
          }else if (B.at(Y - 1).at(X) == 100000000 && B.at(Y).at(X) != 100000000){
            B.at(Y - 1).at(X) = B.at(Y).at(X) + 1;
            Q.push(make_pair(Y - 1, X));
          }else if (C.at(Y - 1).at(X) == 100000000 && C.at(Y).at(X) != 100000000){
            C.at(Y - 1).at(X) = C.at(Y).at(X) + 1;
            Q.push(make_pair(Y - 1, X));
          }
        }
      }
      if (Y != H - 1){
        if (A.at(Y + 1).at(X) != '#'){
          if (B.at(Y + 1).at(X) == 100000000 && B.at(Y).at(X) != 100000000 && C.at(Y + 1).at(X) == 100000000 && C.at(Y).at(X) != 100000000){
            B.at(Y + 1).at(X) = B.at(Y).at(X) + 1;
            C.at(Y + 1).at(X) = C.at(Y).at(X) + 1;
            Q.push(make_pair(Y + 1, X));
          }else if (B.at(Y + 1).at(X) == 100000000 && B.at(Y).at(X) != 100000000){
            B.at(Y + 1).at(X) = B.at(Y).at(X) + 1;
            Q.push(make_pair(Y + 1, X));
          }else if (C.at(Y + 1).at(X) == 100000000 && C.at(Y).at(X) != 100000000){
            C.at(Y + 1).at(X) = C.at(Y).at(X) + 1;
            Q.push(make_pair(Y + 1, X));
          }
        }
      }
      if (X != 0){
        if (A.at(Y).at(X - 1) != '#'){
          if (B.at(Y).at(X - 1) == 100000000 && B.at(Y).at(X) != 100000000 && C.at(Y).at(X - 1) == 100000000 && C.at(Y).at(X) != 100000000){
            B.at(Y).at(X - 1) = B.at(Y).at(X) + 1;
            C.at(Y).at(X - 1) = C.at(Y).at(X) + 1;
            Q.push(make_pair(Y, X - 1));
          }else if (B.at(Y).at(X - 1) == 100000000 && B.at(Y).at(X) != 100000000){
            B.at(Y).at(X - 1) = B.at(Y).at(X) + 1;
            Q.push(make_pair(Y, X - 1));
          }else if (C.at(Y).at(X - 1) == 100000000 && C.at(Y).at(X) != 100000000){
            C.at(Y).at(X - 1) = C.at(Y).at(X) + 1;
            Q.push(make_pair(Y, X - 1));
          }
        }
      }
      if (X != W - 1){
        if (A.at(Y).at(X + 1) != '#'){
          if (B.at(Y).at(X + 1) == 100000000 && B.at(Y).at(X) != 100000000 && C.at(Y).at(X + 1) == 100000000 && C.at(Y).at(X) != 100000000){
            B.at(Y).at(X + 1) = B.at(Y).at(X) + 1;
            C.at(Y).at(X + 1) = C.at(Y).at(X) + 1;
            Q.push(make_pair(Y, X + 1));
          }else if (B.at(Y).at(X + 1) == 100000000 && B.at(Y).at(X) != 100000000){
            B.at(Y).at(X + 1) = B.at(Y).at(X) + 1;
            Q.push(make_pair(Y, X + 1));
          }else if (C.at(Y).at(X + 1) == 100000000 && C.at(Y).at(X) != 100000000){
            C.at(Y).at(X + 1) = C.at(Y).at(X) + 1;
            Q.push(make_pair(Y, X + 1));
          }
        }
      }
    }else if (A.at(Y).at(X) == 'U'){
      if (Y != 0){
        if (A.at(Y - 1).at(X) != '#'){
          if (B.at(Y - 1).at(X) == 100000000 && B.at(Y).at(X) != 100000000 && C.at(Y - 1).at(X) == 100000000 && C.at(Y).at(X) != 100000000){
            B.at(Y - 1).at(X) = B.at(Y).at(X) + 1;
            C.at(Y - 1).at(X) = C.at(Y).at(X) + 1;
            Q.push(make_pair(Y - 1, X));
          }else if (B.at(Y - 1).at(X) == 100000000 && B.at(Y).at(X) != 100000000){
            B.at(Y - 1).at(X) = B.at(Y).at(X) + 1;
            Q.push(make_pair(Y - 1, X));
          }else if (C.at(Y - 1).at(X) == 100000000 && C.at(Y).at(X) != 100000000){
            C.at(Y - 1).at(X) = C.at(Y).at(X) + 1;
            Q.push(make_pair(Y - 1, X));
          }
        }
      }
      if (Y != H - 1){
        if (A.at(Y + 1).at(X) != '#'){
          if (C.at(Y + 1).at(X) == 100000000 && B.at(Y).at(X) != 100000000){
            C.at(Y + 1).at(X) = B.at(Y).at(X) + 1;
            Q.push(make_pair(Y + 1, X));
          }
        }
      }
      if (X != 0){
        if (A.at(Y).at(X - 1) != '#'){
          if (C.at(Y).at(X - 1) == 100000000 && B.at(Y).at(X) != 100000000){
            C.at(Y).at(X - 1) = B.at(Y).at(X) + 1;
            Q.push(make_pair(Y, X - 1));
          }
        }
      }
      if (X != W - 1){
        if (A.at(Y).at(X + 1) != '#'){
          if (C.at(Y).at(X + 1) == 100000000 && B.at(Y).at(X) != 100000000){
            C.at(Y).at(X + 1) = B.at(Y).at(X) + 1;
            Q.push(make_pair(Y, X + 1));
          }
        }
      }
    }else if (A.at(Y).at(X) == 'D'){
      if (Y != 0){
        if (A.at(Y - 1).at(X) != '#'){
          if (C.at(Y - 1).at(X) == 100000000 && B.at(Y).at(X) != 100000000){
            C.at(Y - 1).at(X) = B.at(Y).at(X) + 1;
            Q.push(make_pair(Y - 1, X));
          }
        }
      }
      if (Y != H - 1){
        if (A.at(Y + 1).at(X) != '#'){
          if (B.at(Y + 1).at(X) == 100000000 && B.at(Y).at(X) != 100000000 && C.at(Y + 1).at(X) == 100000000 && C.at(Y).at(X) != 100000000){
            B.at(Y + 1).at(X) = B.at(Y).at(X) + 1;
            C.at(Y + 1).at(X) = C.at(Y).at(X) + 1;
            Q.push(make_pair(Y + 1, X));
          }else if (B.at(Y + 1).at(X) == 100000000 && B.at(Y).at(X) != 100000000){
            B.at(Y + 1).at(X) = B.at(Y).at(X) + 1;
            Q.push(make_pair(Y + 1, X));
          }else if (C.at(Y + 1).at(X) == 100000000 && C.at(Y).at(X) != 100000000){
            C.at(Y + 1).at(X) = C.at(Y).at(X) + 1;
            Q.push(make_pair(Y + 1, X));
          }
        }
      }
      if (X != 0){
        if (A.at(Y).at(X - 1) != '#'){
          if (C.at(Y).at(X - 1) == 100000000 && B.at(Y).at(X) != 100000000){
            C.at(Y).at(X - 1) = B.at(Y).at(X) + 1;
            Q.push(make_pair(Y, X - 1));
          }
        }
      }
      if (X != W - 1){
        if (A.at(Y).at(X + 1) != '#'){
          if (C.at(Y).at(X + 1) == 100000000 && B.at(Y).at(X) != 100000000){
            C.at(Y).at(X + 1) = B.at(Y).at(X) + 1;
            Q.push(make_pair(Y, X + 1));
          }
        }
      }
    }else if (A.at(Y).at(X) == 'L'){
      if (Y != 0){
        if (A.at(Y - 1).at(X) != '#'){
          if (C.at(Y - 1).at(X) == 100000000 && B.at(Y).at(X) != 100000000){
            C.at(Y - 1).at(X) = B.at(Y).at(X) + 1;
            Q.push(make_pair(Y - 1, X));
          }
        }
      }
      if (Y != H - 1){
        if (A.at(Y + 1).at(X) != '#'){
          if (C.at(Y + 1).at(X) == 100000000 && B.at(Y).at(X) != 100000000){
            C.at(Y + 1).at(X) = B.at(Y).at(X) + 1;
            Q.push(make_pair(Y + 1, X));
          }
        }
      }
      if (X != 0){
        if (A.at(Y).at(X - 1) != '#'){
          if (B.at(Y).at(X - 1) == 100000000 && B.at(Y).at(X) != 100000000 && C.at(Y).at(X - 1) == 100000000 && C.at(Y).at(X) != 100000000){
            B.at(Y).at(X - 1) = B.at(Y).at(X) + 1;
            C.at(Y).at(X - 1) = C.at(Y).at(X) + 1;
            Q.push(make_pair(Y, X - 1));
          }else if (B.at(Y).at(X - 1) == 100000000 && B.at(Y).at(X) != 100000000){
            B.at(Y).at(X - 1) = B.at(Y).at(X) + 1;
            Q.push(make_pair(Y, X - 1));
          }else if (C.at(Y).at(X - 1) == 100000000 && C.at(Y).at(X) != 100000000){
            C.at(Y).at(X - 1) = C.at(Y).at(X) + 1;
            Q.push(make_pair(Y, X - 1));
          }
        }
      }
      if (X != W - 1){
        if (A.at(Y).at(X + 1) != '#'){
          if (C.at(Y).at(X + 1) == 100000000 && B.at(Y).at(X) != 100000000){
            C.at(Y).at(X + 1) = B.at(Y).at(X) + 1;
            Q.push(make_pair(Y, X + 1));
          }
        }
      }
    }else if (A.at(Y).at(X) == 'R'){
      if (Y != 0){
        if (A.at(Y - 1).at(X) != '#'){
          if (C.at(Y - 1).at(X) == 100000000 && B.at(Y).at(X) != 100000000){
            C.at(Y - 1).at(X) = B.at(Y).at(X) + 1;
            Q.push(make_pair(Y - 1, X));
          }
        }
      }
      if (Y != H - 1){
        if (A.at(Y + 1).at(X) != '#'){
          if (C.at(Y + 1).at(X) == 100000000 && B.at(Y).at(X) != 100000000){
            C.at(Y + 1).at(X) = B.at(Y).at(X) + 1;
            Q.push(make_pair(Y + 1, X));
          }
        }
      }
      if (X != 0){
        if (A.at(Y).at(X - 1) != '#'){
          if (C.at(Y).at(X - 1) == 100000000 && B.at(Y).at(X) != 100000000){
            C.at(Y).at(X - 1) = B.at(Y).at(X) + 1;
            Q.push(make_pair(Y, X - 1));
          }
        }
      }
      if (X != W - 1){
        if (A.at(Y).at(X + 1) != '#'){
          if (B.at(Y).at(X + 1) == 100000000 && B.at(Y).at(X) != 100000000 && C.at(Y).at(X + 1) == 100000000 && C.at(Y).at(X) != 100000000){
            B.at(Y).at(X + 1) = B.at(Y).at(X) + 1;
            C.at(Y).at(X + 1) = C.at(Y).at(X) + 1;
            Q.push(make_pair(Y, X + 1));
          }else if (B.at(Y).at(X + 1) == 100000000 && B.at(Y).at(X) != 100000000){
            B.at(Y).at(X + 1) = B.at(Y).at(X) + 1;
            Q.push(make_pair(Y, X + 1));
          }else if (C.at(Y).at(X + 1) == 100000000 && C.at(Y).at(X) != 100000000){
            C.at(Y).at(X + 1) = C.at(Y).at(X) + 1;
            Q.push(make_pair(Y, X + 1));
          }
        }
      }
    }
  }
  if (B.at(GY).at(GX) == 100000000 && C.at(GY).at(GX) == 100000000){
    cout << -1 << endl;
  }else{
    cout << min(B.at(GY).at(GX), C.at(GY).at(GX)) << endl;
  }
}
accuracy: 1
time_ms: 10
memory_kb: 5248
final_rank: 7

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define rep(i, n) for (ll i = 0; i < (ll)(n); i++)
#define oke cout << "Yes" << '\n';
#define dame cout << "No" << '\n';
#define all(a) a.begin(), a.end()
#define rall(a) a.rbegin(), a.rend()
using HaiI = vector<vector<int>>;
using Hai2 = vector<vector<ll>>;
using HaiB = vector<vector<bool>>;
using Hai3 = vector<vector<vector<ll>>>;

int main() {
	ios::sync_with_stdio(false);
	cin.tie(nullptr);
	cout << fixed << setprecision(15);
	int H,W;
	cin >> H >> W;
	vector<string>S(H);
	rep(i,H){
		cin >> S[i];
	}

	Hai3 dist(H,Hai2(W,vector<ll>(2,1e9)));
	queue<pair<int,int>>Q;
	pair<int,int>goal;
	rep(i,H){
		rep(j,W){
			if(S[i][j]=='S'){
				Q.push({i,j});
				dist[i][j][0]=0;
			}
			if(S[i][j]=='G'){
				goal={i,j};
			}
		}
	}

	vector<char>goc={'R','L','U','D'};
    vector<int>gox={1,-1,0,0};
    vector<int>goy={0,0,-1,1};

	while(!Q.empty()){
		int y,x;
		tie(y,x)=Q.front();
		Q.pop();
		rep(i,4){
			int xx=x+gox[i],yy=y+goy[i];
			if(xx < 0 || xx >= W || yy < 0 || yy >= H){
            	continue;
        	}
			if(S[yy][xx]=='#') continue;
			if(S[y][x]=='.'||S[y][x]=='S'||S[y][x]=='G'){
				rep(j,2){
					if(dist[y][x][j]+1 < dist[yy][xx][j]){
						dist[yy][xx][j]=dist[y][x][j]+1;
						Q.push({yy,xx});
					}
				}
				continue;
			}
			if(S[y][x]!=goc[i]){
				if(dist[y][x][0]+1 < dist[yy][xx][1]){
					dist[yy][xx][1]=dist[y][x][0]+1;
					Q.push({yy,xx});
				}
			}else{
				rep(k,2){
					if(dist[y][x][k]+1 < dist[yy][xx][k]){
						dist[yy][xx][k]=dist[y][x][k]+1;
						Q.push({yy,xx});
					}
				}
			}
		
			
		}
	}
	ll ans=min(dist[goal.first][goal.second][0],dist[goal.first][goal.second][1]);
	if(ans==1e9)ans=-1;
	cout << ans << "\n";
}
accuracy: 1
time_ms: 10
memory_kb: 8520
final_rank: 12

code_snippet: #include <iostream>
#include <vector>
#include <queue>

using namespace std;

struct cell {
	int x = -1, y = -1, dist = 0;
	bool f = false;
};
int h, w;
vector<vector<vector<bool>>> used;
vector<vector<char>> d;

bool check(int x, int y, bool f) {
	return x >= 0 && y >= 0 && x < h && y < w && !used[x][y][f] && d[x][y] != '#';
}

int main() {
	queue<cell> q;
	cin >> h >> w;
	d.resize(h, vector<char>(w));
	used.resize(h, vector<vector<bool>>(w, vector<bool>(2, 0)));
	const vector<int> dx = { -1, 1, 0, 0 }, dy = { 0, 0, -1, 1 };
	for (int i = 0; i < h; ++i) {
		for (int j = 0; j < w; ++j) {
			cin >> d[i][j];
			if (d[i][j] == 'S') {
				q.push({ i, j, 0, 0 });
				used[i][j] = { 1, 1 };
			}
		}
	}
	while (!q.empty()) {
		cell u = q.front();
		q.pop();
		if (d[u.x][u.y] == 'G') {
			cout << u.dist << '\n';
			return 0;
		}
		for (int i = 0; i < 4; ++i) {
			if (check(u.x + dx[i], u.y + dy[i], u.f)) {
				if (d[u.x][u.y] == '.' || d[u.x][u.y] == 'S'){
					q.push({ u.x + dx[i], u.y + dy[i], u.dist + 1, u.f });
					used[u.x + dx[i]][u.y + dy[i]][u.f] = 1;
				}
				else if (d[u.x][u.y] == 'U') {
					if (dx[i] == -1) {
						q.push({ u.x + dx[i], u.y + dy[i], u.dist + 1, u.f });
						used[u.x + dx[i]][u.y + dy[i]][u.f] = 1;
					}
					else if (u.f == 0) {
						q.push({ u.x + dx[i], u.y + dy[i], u.dist + 1, !u.f });
						used[u.x + dx[i]][u.y + dy[i]][!u.f] = 1;
					}
				}
				else if (d[u.x][u.y] == 'D') {
					if (dx[i] == 1) {
						q.push({ u.x + dx[i], u.y + dy[i], u.dist + 1, u.f });
						used[u.x + dx[i]][u.y + dy[i]][u.f] = 1;
					}
					else if (u.f == 0) {
						q.push({ u.x + dx[i], u.y + dy[i], u.dist + 1, !u.f });
						used[u.x + dx[i]][u.y + dy[i]][!u.f] = 1;
					}
				}
				else if (d[u.x][u.y] == 'L') {
					if (dy[i] == -1) {
						q.push({ u.x + dx[i], u.y + dy[i], u.dist + 1, u.f });
						used[u.x + dx[i]][u.y + dy[i]][u.f] = 1;
					}
					else if (u.f == 0) {
						q.push({ u.x + dx[i], u.y + dy[i], u.dist + 1, !u.f });
						used[u.x + dx[i]][u.y + dy[i]][!u.f] = 1;
					}
				}
				else {
					if (dy[i] == 1) {
						q.push({ u.x + dx[i], u.y + dy[i], u.dist + 1, u.f });
						used[u.x + dx[i]][u.y + dy[i]][u.f] = 1;
					}
					else if (u.f == 0) {
						q.push({ u.x + dx[i], u.y + dy[i], u.dist + 1, !u.f });
						used[u.x + dx[i]][u.y + dy[i]][!u.f] = 1;
					}
				}
			}
		}
	}
	cout << -1 << '\n';
}
accuracy: 1
time_ms: 10
memory_kb: 9928
final_rank: 16

code_snippet: #include <bits/stdc++.h>

using namespace std;

struct cell {
	int x = -1, y = -1, dist = 0;
	bool f = false;
};


cell make_cell(int xn, int yn, int distn, bool fn){
    cell u;
    u.x = xn;
    u.y = yn;
    u.dist = distn;
    u.f = fn;
    return u;
}

int h, w;
vector<vector<vector<bool>>> used;
vector<vector<char>> d;

bool check(int x, int y, bool f) {
	return x >= 0 && y >= 0 && x < h && y < w && !used[x][y][f] && d[x][y] != '#';
}

int main() {
	queue<cell> q;
	cin >> h >> w;
	d.resize(h, vector<char>(w));
	used.resize(h, vector<vector<bool>>(w, vector<bool>(2, 0)));
	const vector<int> dx = { -1, 1, 0, 0 }, dy = { 0, 0, -1, 1 };
	for (int i = 0; i < h; ++i) {
		for (int j = 0; j < w; ++j) {
			cin >> d[i][j];
			if (d[i][j] == 'S') {
				q.push(make_cell( i, j, 0, false ));
				used[i][j] = { 1, 1 };
			}
		}
	}
	while (!q.empty()) {
		cell u = q.front();
		q.pop();
		if (d[u.x][u.y] == 'G') {
			cout << u.dist << '\n';
			return 0;
		}
		for (int i = 0; i < 4; ++i) {
			if (check(u.x + dx[i], u.y + dy[i], u.f)) {
				if (d[u.x][u.y] == '.' || d[u.x][u.y] == 'S'){
					q.push(make_cell( u.x + dx[i], u.y + dy[i], u.dist + 1, u.f ));
					used[u.x + dx[i]][u.y + dy[i]][u.f] = 1;
				}
				else if (d[u.x][u.y] == 'U') {
					if (dx[i] == -1) {
						q.push(make_cell( u.x + dx[i], u.y + dy[i], u.dist + 1, u.f ));
						used[u.x + dx[i]][u.y + dy[i]][u.f] = 1;
					}
					else if (u.f == 0) {
						q.push(make_cell( u.x + dx[i], u.y + dy[i], u.dist + 1, !u.f ));
						used[u.x + dx[i]][u.y + dy[i]][!u.f] = 1;
					}
				}
				else if (d[u.x][u.y] == 'D') {
					if (dx[i] == 1) {
						q.push(make_cell( u.x + dx[i], u.y + dy[i], u.dist + 1, u.f ));
						used[u.x + dx[i]][u.y + dy[i]][u.f] = 1;
					}
					else if (u.f == 0) {
						q.push(make_cell( u.x + dx[i], u.y + dy[i], u.dist + 1, !u.f ));
						used[u.x + dx[i]][u.y + dy[i]][!u.f] = 1;
					}
				}
				else if (d[u.x][u.y] == 'L') {
					if (dy[i] == -1) {
						q.push(make_cell( u.x + dx[i], u.y + dy[i], u.dist + 1, u.f ));
						used[u.x + dx[i]][u.y + dy[i]][u.f] = 1;
					}
					else if (u.f == 0) {
						q.push(make_cell( u.x + dx[i], u.y + dy[i], u.dist + 1, !u.f ));
						used[u.x + dx[i]][u.y + dy[i]][!u.f] = 1;
					}
				}
				else {
					if (dy[i] == 1) {
						q.push(make_cell( u.x + dx[i], u.y + dy[i], u.dist + 1, u.f ));
						used[u.x + dx[i]][u.y + dy[i]][u.f] = 1;
					}
					else if (u.f == 0) {
						q.push(make_cell( u.x + dx[i], u.y + dy[i], u.dist + 1, !u.f ));
						used[u.x + dx[i]][u.y + dy[i]][!u.f] = 1;
					}
				}
			}
		}
	}
	cout << -1 << '\n';
	return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 9912
final_rank: 15

code_snippet: #include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
typedef unsigned long long int ull;
#define chmin(x,y) x = min(x,y)
#define chmax(x,y) x = max(x,y)
#define BIG_NUM 2000000000
#define HUGE_NUM 4000000000000000000 //オーバーフローに注意
#define MOD 1000000007
#define EPS 0.000000001



#define SIZE 305

struct Info{
	Info(){

		row = col = sum_dist = 0;
		FLG = is_pre = false;
	}
	Info(int arg_row,int arg_col,int arg_sum_dist,bool arg_FLG,bool arg_is_pre){
		row = arg_row;
		col = arg_col;
		sum_dist = arg_sum_dist;
		FLG = arg_FLG;
		is_pre = arg_is_pre;
	}
	bool operator<(const struct Info& arg) const{

		return sum_dist > arg.sum_dist; //昇順(PQ)
	}

	int row,col,sum_dist;
	bool FLG,is_pre;
};


int H,W;
int d_row[4] = {-1,0,0,1},d_col[4] = {0,-1,1,0};
int min_dist[SIZE][SIZE][2][2];
char buf[SIZE][SIZE];

bool rangeCheck(int row,int col){


	return row >= 0 && row <= H-1 && col >= 0 && col <= W-1;
}

int main(){

	scanf("%d %d",&H,&W);

	int s_row,s_col,g_row,g_col;

	for(int row = 0; row < H; row++){

		scanf("%s",buf[row]);
		for(int col = 0; col < W; col++){
			if(buf[row][col] == 'S'){

				s_row = row;
				s_col = col;

			}else if(buf[row][col] == 'G'){

				g_row = row;
				g_col = col;
			}
		}
	}

	for(int row = 0; row < H; row++){
		for(int col = 0; col < W; col++){
			for(int a = 0; a < 2; a++){
				for(int b = 0; b < 2; b++){

					min_dist[row][col][a][b] = BIG_NUM;
				}
			}
		}
	}

	min_dist[s_row][s_col][false][false] = 0;
	priority_queue<Info> Q;
	Q.push(Info(s_row,s_col,0,false,false));

	while(!Q.empty()){

		Info info = Q.top();
		Q.pop();

		if(info.row == g_row && info.col == g_col){

			printf("%d\n",info.sum_dist);
			return 0;
		}

		if(info.sum_dist > min_dist[info.row][info.col][info.FLG][info.is_pre])continue;

		if(info.is_pre || buf[info.row][info.col] == '.' || buf[info.row][info.col] == 'S'){ //自由に動ける

			for(int i = 0; i < 4; i++){

				int adj_row = info.row+d_row[i];
				int adj_col = info.col+d_col[i];
				if(!rangeCheck(adj_row,adj_col) || buf[adj_row][adj_col] == '#')continue;

				int next_dist = info.sum_dist+1;

				if(buf[adj_row][adj_col] == '.' || buf[adj_row][adj_col] == 'G' || buf[adj_row][adj_col] == 'S'){

					if(min_dist[adj_row][adj_col][info.FLG][false] > next_dist){

						min_dist[adj_row][adj_col][info.FLG][false] = next_dist;
						Q.push(Info(adj_row,adj_col,next_dist,info.FLG,false));
					}

				}else{ //一方向マス

					//方向転換しない
					if(min_dist[adj_row][adj_col][info.FLG][false] > next_dist){

						min_dist[adj_row][adj_col][info.FLG][false] = next_dist;
						Q.push(Info(adj_row,adj_col,next_dist,info.FLG,false));
					}
					//方向転換する
					if(!info.FLG && min_dist[adj_row][adj_col][true][true] > next_dist){

						min_dist[adj_row][adj_col][true][true] = next_dist;
						Q.push(Info(adj_row,adj_col,next_dist,true,true));
					}
				}
			}

		}else{

			int adj_row,adj_col;
			switch(buf[info.row][info.col]){
			case 'U':
				adj_row = info.row-1;
				adj_col = info.col;
				break;
			case 'D':
				adj_row = info.row+1;
				adj_col = info.col;
				break;
			case 'R':
				adj_row = info.row;
				adj_col = info.col+1;
				break;
			case 'L':
				adj_row = info.row;
				adj_col = info.col-1;
				break;
			}
			if(!rangeCheck(adj_row,adj_col) || buf[adj_row][adj_col] == '#')continue;

			int next_dist = info.sum_dist+1;

			if(buf[adj_row][adj_col] == '.' || buf[adj_row][adj_col] == 'G'|| buf[adj_row][adj_col] == 'S'){ //方向転換不要

				if(min_dist[adj_row][adj_col][info.FLG][false] > next_dist){

					min_dist[adj_row][adj_col][info.FLG][false] = next_dist;
					Q.push(Info(adj_row,adj_col,next_dist,info.FLG,false));
				}

			}else{ //一方向マス

				//方向転換しない
				if(min_dist[adj_row][adj_col][info.FLG][false] > next_dist){

					min_dist[adj_row][adj_col][info.FLG][false] = next_dist;
					Q.push(Info(adj_row,adj_col,next_dist,info.FLG,false));
				}
				//方向転換する
				if(!info.FLG && min_dist[adj_row][adj_col][true][true] > next_dist){

					min_dist[adj_row][adj_col][true][true] = next_dist;
					Q.push(Info(adj_row,adj_col,next_dist,true,true));
				}
			}
		}
	}

	printf("-1\n");

	return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 5028
final_rank: 5

code_snippet: #include "bits/stdc++.h"
using namespace std;
#define int long long
#define rep(i, n) for (int i = 0; i < n; i++)
#define ll long long
int h, w;
vector<vector<int>> cost(vector<vector<char>> s, int s2, int s3, int p) {
  vector<vector<int>> seen(h + 1, vector<int>(w + 1, -1));
  seen[s2][s3] = 0;
  queue<pair<int, int>> que;
  vector<int> x = {0, 0, 1, -1};
  vector<int> y = {1, -1, 0, 0};
  que.push({s2, s3});
  while (!que.empty()) {
    int posx = que.front().first;
    int posy = que.front().second;
    que.pop();
    rep(t, 4) {
      int i = posx + x[t];
      int j = posy + y[t];
      if (p == 0) {
        if (s[posx][posy] == 'U') {
          i = posx - 1;
          j = posy;
        }
        if (s[posx][posy] == 'D') {
          i = posx + 1;
          j = posy;
        }
        if (s[posx][posy] == 'L') {
          i = posx;
          j = posy - 1;
        }
        if (s[posx][posy] == 'R') {
          i = posx;
          j = posy + 1;
        }
      }
      if (i < 0 || i >= h)
        continue;
      if (j < 0 || j >= w)
        continue;
      if (p == 1) {
        if (s[i][j] == 'U') {
          if (!(posx - i == 1 && posy - j == 0))
            continue;
        }
        if (s[i][j] == 'D') {
          if (!(posx - i == -1 && posy - j == 0))
            continue;
        }
        if (s[i][j] == 'L') {
          if (!(posx - i == 0 && posy - j == 1))
            continue;
        }
        if (s[i][j] == 'R') {
          if (!(posx - i == 0 && posy - j == -1))
            continue;
        }
      }
      if (s[i][j] == '#')
        continue;
      if (seen[i][j] != -1) {
        continue;
      }

      seen[i][j] = seen[posx][posy] + 1;
      que.push({i, j});
    }
  }
  return seen;
}
signed main() {
  int s2, s3;
  int g1, g2;
  cin >> h >> w;
  vector<vector<char>> s(h + 1, vector<char>(w + 1));
  vector<vector<char>> s1(h + 1, vector<char>(w + 1));

  rep(i, h) { rep(j, w) cin >> s[i][j]; }
  s1 = s;
  rep(i, h) {
    rep(j, w) {
      if (s[i][j] == 'U')
        s1[i][j] = 'D';
      if (s[i][j] == 'D')
        s1[i][j] = 'U';
      if (s[i][j] == 'R')
        s1[i][j] = 'L';
      if (s[i][j] == 'L')
        s1[i][j] = 'R';
      if (s[i][j] == 'S') {
        s2 = i;
        s3 = j;
      }
      if (s[i][j] == 'G') {
        g1 = i;
        g2 = j;
      }
    }
  }
  vector<vector<int>> k = cost(s, s2, s3, 0);

  vector<vector<int>> k1 = cost(s1, g1, g2, 1);

  vector<int> x = {0, 0, 1, -1};
  vector<int> y = {1, -1, 0, 0};
  int ans = 9e18;
  if (k[g1][g2] != -1)
    ans = k[g1][g2];
  rep(i, h) {
    rep(j, w) {
      if (s[i][j] == 'L') {
        rep(t, 4) {

          int posx = i + x[t];
          int posy = j + y[t];
          if (posx < 0 || posx >= h)
            continue;
          if (posy < 0 || posy >= w)
            continue;
          if (k[i][j] == -1 || k1[posx][posy] == -1)
            continue;
          ans = min(ans, k[i][j] + k1[posx][posy] + 1);
        }
      }
      if (s[i][j] == 'R') {
        rep(t, 4) {

          int posx = i + x[t];
          int posy = j + y[t];
          if (posx < 0 || posx >= h)
            continue;
          if (posy < 0 || posy >= w)
            continue;
          if (k[i][j] == -1 || k1[posx][posy] == -1)
            continue;
          ans = min(ans, k[i][j] + k1[posx][posy] + 1);
        }
      }
      if (s[i][j] == 'U') {
        rep(t, 4) {

          int posx = i + x[t];
          int posy = j + y[t];
          if (posx < 0 || posx >= h)
            continue;
          if (posy < 0 || posy >= w)
            continue;
          if (k[i][j] == -1 || k1[posx][posy] == -1)
            continue;
          ans = min(ans, k[i][j] + k1[posx][posy] + 1);
        }
      }
      if (s[i][j] == 'D') {
        rep(t, 4) {

          int posx = i + x[t];
          int posy = j + y[t];
          if (posx < 0 || posx >= h)
            continue;
          if (posy < 0 || posy >= w)
            continue;
          if (k[i][j] == -1 || k1[posx][posy] == -1)
            continue;
          ans = min(ans, k[i][j] + k1[posx][posy] + 1);
        }
      }
    }
  }
  if (ans == 9e18)
    cout << -1 << endl;
  else
    cout << ans << endl;
}
accuracy: 1
time_ms: 10
memory_kb: 5112
final_rank: 6

code_snippet: //  author: Kurose Yuichiro

#include <bits/stdc++.h>
using namespace std;

const int INF = 1001001001;
const int dy[4] = {0, -1, 0, 1};
const int dx[4] = {1, 0, -1, 0};

int H, W;
char s[309][309];
int sy, sx, gy, gx;
int dist[309][309][2];
queue<vector<int>> Q;
int ans;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cin >> H >> W;
    for (int i = 0; i < H; i++) {
        for (int j = 0; j < W; j++) {
            cin >> s[i][j];
            if (s[i][j] == 'S') {
                sy = i;
                sx = j;
            }
            if (s[i][j] == 'G') {
                gy = i;
                gx = j;
            }
        }
    }
    for (int i = 0; i < H; i++) {
        for (int j = 0; j < W; j++) {
            for (int k = 0; k < 2; k++) {
                dist[i][j][k] = INF;
            }
        }
    }
    Q.push({sy, sx, 0});
    dist[sy][sx][0] = 0;
    while (!Q.empty()) {
        auto front = Q.front();
        int y = front[0];
        int x = front[1];
        int k = front[2];
        Q.pop();
        for (int dir = 0; dir < 4; dir++) {
            int ny = y + dy[dir];
            int nx = x + dx[dir];
            if (ny < 0 || ny >= H || nx < 0 || nx >= W) continue;
            if (s[ny][nx] == '#') continue;
            char c;
            switch (dir) {
            case 0: c = 'R'; break;
            case 1: c = 'U'; break;
            case 2: c = 'L'; break;
            case 3: c = 'D'; break;
            default: break;
            }
            if (s[y][x] == '.' || s[y][x] == c || s[y][x] == 'S' || s[y][x] == 'G') {
                if (dist[ny][nx][k] != INF) continue;
                Q.push({ny, nx, k});
                dist[ny][nx][k] = dist[y][x][k] + 1;
            }
            else if (k == 0) {
                if (dist[ny][nx][k + 1] != INF) continue;
                Q.push({ny, nx, k + 1});
                dist[ny][nx][k + 1] = dist[y][x][k] + 1;
            }
        }
    }
    ans = min(dist[gy][gx][0], dist[gy][gx][1]);
    if (ans == INF) ans = -1;
    cout << ans << endl;
    return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 4256
final_rank: 1

code_snippet: //  author: Kurose Yuichiro

#include <bits/stdc++.h>
using namespace std;

const int INF = 1001001001;
const int dy[4] = {0, -1, 0, 1};
const int dx[4] = {1, 0, -1, 0};

int H, W;
char s[309][309];
int sy, sx, gy, gx;
int dist[309][309][2];
queue<vector<int>> Q;
int ans;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cin >> H >> W;
    for (int i = 0; i < H; i++) {
        for (int j = 0; j < W; j++) {
            cin >> s[i][j];
            if (s[i][j] == 'S') {
                sy = i;
                sx = j;
            }
            if (s[i][j] == 'G') {
                gy = i;
                gx = j;
            }
        }
    }
    for (int i = 0; i < H; i++) {
        for (int j = 0; j < W; j++) {
            for (int k = 0; k < 2; k++) {
                dist[i][j][k] = INF;
            }
        }
    }
    Q.push({sy, sx, 0});
    dist[sy][sx][0] = 0;
    while (!Q.empty()) {
        auto front = Q.front();
        int y = front[0];
        int x = front[1];
        int k = front[2];
        Q.pop();
        for (int dir = 0; dir < 4; dir++) {
            int ny = y + dy[dir];
            int nx = x + dx[dir];
            if (ny < 0 || ny >= H || nx < 0 || nx >= W) continue;
            if (s[ny][nx] == '#') continue;
            char c;
            switch (dir) {
            case 0: c = 'R'; break;
            case 1: c = 'U'; break;
            case 2: c = 'L'; break;
            case 3: c = 'D'; break;
            default: break;
            }
            if (k == 0) {
                if (s[y][x] == '.' || s[y][x] == c || s[y][x] == 'S' || s[y][x] == 'G') {
                    if (dist[ny][nx][0] != INF) continue;
                    Q.push({ny, nx, 0});
                    dist[ny][nx][0] = dist[y][x][0] + 1;
                }
                else {
                    if (dist[ny][nx][1] != INF) continue;
                    Q.push({ny, nx, 1});
                    dist[ny][nx][1] = dist[y][x][0] + 1;
                }
            }
            else {
                if (s[y][x] == '.' || s[y][x] == c || s[y][x] == 'S' || s[y][x] == 'G') {
                    if (dist[ny][nx][1] != INF) continue;
                    Q.push({ny, nx, 1});
                    dist[ny][nx][1] = dist[y][x][1] + 1;
                }
            }
        }
    }
    ans = min(dist[gy][gx][0], dist[gy][gx][1]);
    if (ans == INF) ans = -1;
    cout << ans << endl;
    return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 4320
final_rank: 3

code_snippet: #include <bits/stdc++.h>
using namespace std;

int main(){
	int h,w;
	cin >> h >> w;
	vector<vector<char>> s(h,vector<char>(w));
	pair<pair<int,int>,pair<int,int>> P;
	for(int i = 0;i < h;i++){
		string S;
		cin >> S;
		for(int j = 0;j < w;j++){
			s[i][j] = S[j];
			if(s[i][j] == 'S'){
				P.first = {i,j};
			}
			if(s[i][j] == 'G'){
				P.second = {i,j};
			}
		}
	}
	vector<vector<vector<int>>> t(h,vector<vector<int>>(w,vector<int>(2,INT_MAX)));
	t[P.first.first][P.first.second][0] = 0;
	vector<int> dx = {-1,0,1,0};
	vector<int> dy = {0,-1,0,1};
	queue<pair<pair<int,int>,int>> q;
	q.push({P.first,0});
	while(!q.empty()){
		pair<pair<int,int>,int> it = q.front();
		q.pop();
		for(int i = 0;i < 4;i++){
			pair<int,int> nex = {it.first.first + dy[i],it.first.second + dx[i]};
			if(nex.first < 0 || nex.first >= h || nex.second < 0 || nex.second >= w) continue;
			if(s[nex.first][nex.second] == '#') continue;
			int p = it.second;
			if(s[it.first.first][it.first.second] == 'L' && i != 0){
				p++;
			}
			if(s[it.first.first][it.first.second] == 'U' && i != 1){
				p++;
			}
			if(s[it.first.first][it.first.second] == 'R' && i != 2){
				p++;
			}
			if(s[it.first.first][it.first.second] == 'D' && i != 3){
				p++;
			}
			if(p >= 2) continue;
			if(t[nex.first][nex.second][p] != INT_MAX) continue;
			t[nex.first][nex.second][p] = t[it.first.first][it.first.second][it.second] + 1;
			q.push({nex,p});
		}
	}
	int ans = min(t[P.second.first][P.second.second][0],t[P.second.first][P.second.second][1]);
	if(ans == INT_MAX){
		cout << -1 << endl;
	}else{
		cout << ans << endl;
	}
}
accuracy: 1
time_ms: 10
memory_kb: 8344
final_rank: 10

code_snippet: #include <bits/stdc++.h>
#define asb(a,b) ((a)-(b)>0?(a)-(b):(b)-(a))
#define atio(v,n) for(int g=0;g<(n);++g)cin >> v[g]
#define atdp(v,en) {int bbbbbb=0;for(auto o:v){if(bbbbbb)cout << en;bbbbbb=1;cout << o;}cout << endl;}
#define atfs(a) printf("%lld %lld\n",(a).first,(a).second)
#define ri(n) rp(i,n)
#define rj(n) rp(j,n)
#define rk(n) rp(k,n)
#define rl(n) rp(l,n)
#define rp(e,c) for(int e=0;e<(c);++e)
#define rix(s,h) rpx(i,s,h)
#define rjx(s,h) rpx(j,s,h)
#define rkx(s,h) rpx(k,s,h)
#define rlx(s,h) rpx(l,s,h)
#define rpx(e,s,h) for(int e=s;e<(h);++e)
#define ci(d,r) ((d)/(r)+(((d)%(r))!=0))
#define pn {pr("No");return 0;}
#define py {pr("Yes");return 0;}
#define pr(a) cout << a << endl
#define bgen(a) a.begin(),a.end()
#define INF 114514810
#define asr(q,n) (0<=(q) && (q)<(n))
using namespace std;
using ll=long long;
using vi=vector<int>;
using vll=vector<ll>;
using pii=pair<int,int>;
using pll=pair<ll,ll>;
using si=set<int>;
using sll=set<ll>;
using qi=queue<int>;
using qll=queue<ll>;
using qpii=queue<pii>;
using qpll=queue<pll>;
using vst=vector<string>;
using vsi=vector<si>;
using vvi=vector<vi>;
using vvl=vector<vll>;
using tiii=tuple<int,int,int>;
using tiiii=tuple<int,int,int,int>;
using tlll=tuple<ll,ll,ll>;
using mii=map<int,int>;
using mll=map<ll,ll>;
using stki=stack<int>;
using stkll=stack<ll>;
int dx[4]={1,0,-1,0};
int dy[4]={0,-1,0,1};
int main(){
  // オーバーフロー気をつけろ
  int h,w;
  cin >> h >> w;
  vst s(h);
  atio(s,h);
  int y1,x1,y2,x2;
  ri(h)rj(w){
    if(s[i][j]=='S'){
      y1=i,x1=j;
      s[i][j]='.';
    }else if(s[i][j]=='G'){
      y2=i,x2=j;
      s[i][j]='.';
    }
  }
  char cv[128];
  cv['R']=0;
  cv['U']=1;
  cv['L']=2;
  cv['D']=3;
  vector<vector<vi>> bcost(h,vector<vi>(w,vi(2,INF)));
  priority_queue<tiiii,vector<tiiii>,greater<tiiii>> dij;
  bcost[y1][x1][0]=0;
  bcost[y1][x1][1]=0;
  dij.push(tiiii(0,y1,x1,0));
  while(dij.size()){
    tiiii tmp=dij.top();
    int ccost=get<0>(tmp);
    int y=get<1>(tmp);
    int x=get<2>(tmp);
    int k=get<3>(tmp);
    dij.pop();
    if(bcost[y][x][k]<ccost)continue;
    int ncost=ccost+1;
    if(s[y][x]=='.'){
      ri(4){
        int ty=y+dy[i];
        int tx=x+dx[i];
        if(asr(ty,h)&&asr(tx,w)){
          if(bcost[ty][tx][k]>ncost){
            bcost[ty][tx][k]=ncost;
            dij.push(tiiii(ncost,ty,tx,k));
          }
        }
      }
    }else if(s[y][x]!='#'){
      int cd=cv[s[y][x]];
      ri(4){
        int nk=k;
        if(cd!=i){
          if(k)continue;
          nk=1;
        }
        int ty=y+dy[i];
        int tx=x+dx[i];
        if(asr(ty,h)&&asr(tx,w)){
          if(bcost[ty][tx][nk]>ncost){
            bcost[ty][tx][nk]=ncost;
            dij.push(tiiii(ncost,ty,tx,nk));
          }
        }
      }
    }
  }
  int ans=min(bcost[y2][x2][0],bcost[y2][x2][1]);
  if(ans==INF)ans=-1;
  pr(ans);
}
accuracy: 1
time_ms: 20
memory_kb: 8088
final_rank: 14

code_snippet: #include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define MAX 1000000007

vector<vector<int>> dir = {
    {0,1},
    {0,-1},
    {1,0},
    {-1,0}
};

int main(void){
    int h,w;
    cin >> h >> w;
    vector<vector<char> > m(h+2,vector<char>(w+2,'#'));
    vector<vector<vector<int> > > bfs(2,vector<vector<int> >(h+2,vector<int>(w+2,-1)));
    queue<vector<int> > q;
    
    int ansx,ansy;
    
    rep(i,h){
        rep(j,w){
            char c;
            cin >> c;
            m[i+1][j+1] = c;
            if(c == 'S'){ q.push({i+1,j+1,0}); bfs[0][i+1][j+1] = 0;}
            if(c == 'G'){ ansx = i+1; ansy = j+1; }
        }
    }
    
    while(!q.empty()){
        vector<int> x = q.front();
        q.pop();
        
        rep(i,4){
            int nx = x[0]+dir[i][0],ny = x[1]+dir[i][1];
            switch(m[x[0]][x[1]]){
                case '.':
                case 'S':
                    if(m[nx][ny] != '#' && bfs[x[2]][nx][ny] == -1){
                        bfs[x[2]][nx][ny] = bfs[x[2]][x[0]][x[1]] + 1;
                        q.push({nx,ny,x[2]});
                    }
                    break;
                case 'G':
                    break;
                default:
                    if( (m[x[0]][x[1]] == 'D' && i == 2) || (m[x[0]][x[1]] == 'U' && i == 3) || (m[x[0]][x[1]] == 'R' && i == 0) || (m[x[0]][x[1]] == 'L' && i == 1) ){
                        if(m[nx][ny] != '#' && bfs[x[2]][nx][ny] == -1){
                            bfs[x[2]][nx][ny] = bfs[x[2]][x[0]][x[1]] + 1;
                            q.push({nx,ny,x[2]});
                        }
                    }else{
                        if(x[2] == 1) break;
                        if(m[nx][ny] != '#' && bfs[1][nx][ny] == -1){
                            bfs[1][nx][ny] = bfs[0][x[0]][x[1]] + 1;
                            q.push({nx,ny,1});
                        }
                    }
                    break;
            }
        }
    }
    
    if(bfs[0][ansx][ansy] == -1){
        if(bfs[1][ansx][ansy] == -1){
            cout << -1 << endl;
        }else{
            cout << bfs[1][ansx][ansy] << endl;
        }
    }else{
        if(bfs[1][ansx][ansy] == -1){
            cout << bfs[0][ansx][ansy] << endl;
        }else{
            cout << min(bfs[0][ansx][ansy],bfs[1][ansx][ansy]) << endl;
        }
    }
}
accuracy: 1
time_ms: 10
memory_kb: 4420
final_rank: 4

code_snippet: #include<bits/stdc++.h>
using namespace std;
using ll = long long;
int main(){
  int H,W;
  cin >> H >> W;
  vector<string> S(H);
  for(int i=0;i<H;i++){
    cin >> S[i];
  }
  int sx;
  int sy;
  int gx;
  int gy;
  for(int i=0;i<H;i++){
    for(int j=0;j<W;j++){
      if(S[i][j]=='S'){
        sx = j;
        sy = i;
      }else if(S[i][j]=='G'){
        gx = j;
        gy = i;
      }
    }
  }
  vector<vector<int>> sp(H,vector<int>(W,1e9));
  sp[sy][sx] = 0;
  priority_queue<pair<int,int>,vector<pair<int,int>>,greater<pair<int,int>>> pq;
  pq.push(pair(sp[sy][sx],sy*W+sx));
  while(pq.size()>0){
    pair<int,int> p = pq.top();
    pq.pop();
    int v = p.first;
    int i = p.second/W;
    int j = p.second%W;
    if(v!=sp[i][j]) continue;
    if(S[i][j]=='U'){
      if(i>0){
        if(S[i-1][j]!='#'){
          if(sp[i-1][j]>sp[i][j]+1){
            sp[i-1][j] = sp[i][j]+1;
            pq.push(pair(sp[i-1][j],(i-1)*W+j));
          }
        }
      }
    }else if(S[i][j]=='D'){
      if(i<H-1){
        if(S[i+1][j]!='#'){
          if(sp[i+1][j]>sp[i][j]+1){
            sp[i+1][j] = sp[i][j]+1;
            pq.push(pair(sp[i+1][j],(i+1)*W+j));
          }
        }
      }
    }else if(S[i][j]=='L'){
      if(j>0){
        if(S[i][j-1]!='#'){
          if(sp[i][j-1]>sp[i][j]+1){
            sp[i][j-1] = sp[i][j]+1;
            pq.push(pair(sp[i][j-1],i*W+j-1));
          }
        }
      }
    }else if(S[i][j]=='R'){
      if(j<W-1){
        if(S[i][j+1]!='#'){
          if(sp[i][j+1]>sp[i][j]+1){
            sp[i][j+1] = sp[i][j]+1;
            pq.push(pair(sp[i][j+1],i*W+j+1));
          }
        }
      }
    }else{
      if(i>0){
        if(S[i-1][j]!='#'){
          if(sp[i-1][j]>sp[i][j]+1){
            sp[i-1][j] = sp[i][j]+1;
            pq.push(pair(sp[i-1][j],(i-1)*W+j));
          }
        }
      }
      if(i<H-1){
        if(S[i+1][j]!='#'){
          if(sp[i+1][j]>sp[i][j]+1){
            sp[i+1][j] = sp[i][j]+1;
            pq.push(pair(sp[i+1][j],(i+1)*W+j));
          }
        }
      }
      if(j>0){
        if(S[i][j-1]!='#'){
          if(sp[i][j-1]>sp[i][j]+1){
            sp[i][j-1] = sp[i][j]+1;
            pq.push(pair(sp[i][j-1],i*W+j-1));
          }
        }
      }
      if(j<W-1){
        if(S[i][j+1]!='#'){
          if(sp[i][j+1]>sp[i][j]+1){
            sp[i][j+1] = sp[i][j]+1;
            pq.push(pair(sp[i][j+1],i*W+j+1));
          }
        }
      }
    }
  }
  vector<vector<int>> gp(H,vector<int>(W,1e9));
  gp[gy][gx] = 0;
  pq.push(pair(gp[gy][gx],gy*W+gx));
  while(pq.size()>0){
    pair<int,int> p = pq.top();
    pq.pop();
    int v = p.first;
    int i = p.second/W;
    int j = p.second%W;
    if(v!=gp[i][j]) continue;
    if(i>0){
      if(S[i-1][j]=='D'||S[i-1][j]=='.'){
        if(gp[i-1][j]>v+1){
          gp[i-1][j] = v+1;
          pq.push(pair(gp[i-1][j],(i-1)*W+j));
        }
      }
    }
    if(i<H-1){
      if(S[i+1][j]=='U'||S[i+1][j]=='.'){
        if(gp[i+1][j]>v+1){
          gp[i+1][j] = v+1;
          pq.push(pair(gp[i+1][j],(i+1)*W+j));
        }
      }
    }
    if(j>0){
      if(S[i][j-1]=='R'||S[i][j-1]=='.'){
        if(gp[i][j-1]>v+1){
          gp[i][j-1] = v+1;
          pq.push(pair(gp[i][j-1],i*W+j-1));
        }
      }
    }
    if(j<W-1){
      if(S[i][j+1]=='L'||S[i][j+1]=='.'){
        if(gp[i][j+1]>v+1){
          gp[i][j+1] = v+1;
          pq.push(pair(gp[i][j+1],i*W+j+1));
        }
      }
    }
  }
  int ans = 1e9;
  for(int i=0;i<H;i++){
    for(int j=0;j<W;j++){
      if(S[i][j]=='#') continue;
      if(i>0) ans = min(ans,sp[i][j]+gp[i-1][j]+1);
      if(i<H-1) ans = min(ans,sp[i][j]+gp[i+1][j]+1);
      if(j>0) ans = min(ans,sp[i][j]+gp[i][j-1]+1);
      if(j<W-1) ans = min(ans,sp[i][j]+gp[i][j+1]+1);
    }
  }
  if(ans==1e9) cout << -1 << endl;
  else cout << ans << endl;
}
accuracy: 1
time_ms: 10
memory_kb: 4316
final_rank: 2

code_snippet: #include<iostream>
#include<vector>
#include<algorithm>
#include<string>
#include<set>
#include<queue>
#include<cassert>
using namespace std;
using ll = long long;
#define rep(i,N) for(int i=0;i<N;i++)
using vi=vector<int>;
using vvi=vector<vi>;
using vvvi=vector<vvi>;

struct Node{
    int i,j,k;
    Node(){}
    Node(int i,int j,int k):i(i),j(j),k(k){}
};

int di[4]={1,0,-1,0};
int dj[4]={0,-1,0,1};
string houk="DLUR";
const int INF=2e9;

int main() {
    int H,W;cin>>H>>W;
    vector<string> S(H);
    rep(i,H)cin>>S[i];
    vvvi dp(H,vvi(W,vi(2,INF)));
    queue<pair<int,Node>>q;
    Node start,goal;
    rep(i,H)rep(j,W){
        if(S[i][j]=='S')start=Node(i,j,0);
        if(S[i][j]=='G')goal=Node(i,j,0);
    }
    q.emplace(0,start);
    {
        while(!q.empty()){
            int c=q.front().first;
            int i=q.front().second.i;
            int j=q.front().second.j;
            int k=q.front().second.k;
            q.pop();
            if(c>=dp[i][j][k])continue;
            dp[i][j][k]=c;
            rep(d,4){
                int ni=i+di[d];
                int nj=j+dj[d];
                char s=S[i][j];
                if(s=='U'||s=='R'||s=='L'||s=='D'){
                    if(houk[d]!=s){
                        if(k==1)continue;
                        if(ni<0||nj<0||ni>=H||nj>=W)continue;
                        if(S[ni][nj]=='#')continue;
                        Node nex=Node(ni,nj,k+1);
                        if(dp[ni][nj][k+1]>c+1)q.emplace(c+1,nex);
                        continue;
                    }
                }
                if(ni<0||nj<0||ni>=H||nj>=W)continue;
                if(S[ni][nj]=='#')continue;
                Node nex=Node(ni,nj,k);
                if(dp[ni][nj][k]>c+1)
                q.emplace(c+1,nex);
            }
        }
    }
    int ans=dp[goal.i][goal.j][0];
    ans=min(ans,dp[goal.i][goal.j][1]);
    if(ans==INF)ans=-1;
    cout<<ans<<endl;
    return 0;
}

/*
2 3
SL.
#LG

3 1
G
D
S

3 1
S
U
G

1 3
SLG

1 3
GRS
*/
accuracy: 1
time_ms: 10
memory_kb: 8468
final_rank: 11

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using Graph = vector<vector<int>>;
int H, W;
int cast(int x, int y) {
	return (W * x) + y;
}
void BFS(Graph& G, vector<int>& dist, int st) {
	dist[st] = 0;
	queue<int> que;que.push(st);
	while (!que.empty()) {
		int v = que.front();que.pop();
		for (auto nv : G[v]) {
			if (dist[nv] == -1) {
				dist[nv] = dist[v] + 1;
				que.push(nv);
			}
		}
	}
}
int main() {
	cin >> H >> W;
	Graph G(H * W);
	vector<string> S(H);
	for (int i = 0;i < H;i++) cin >> S[i];
	vector<pair<int, int>> vecs = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
	int st = -1;int gl = -1;
	for (int i = 0;i < H;i++) for (int j = 0;j < W;j++) {
		if (S[i][j] == '#') continue;
		if (S[i][j] == 'S') {
			st = (W * i) + j;
		} else if (S[i][j] == 'G'){
			gl = (W * i) + j;
		}
		int now = (W * i) + j;
		if (S[i][j] == 'S' || S[i][j] == 'G' || S[i][j] == '.') {
			for (auto vc : vecs) {
				int nx = i + vc.first;int ny = j + vc.second;
				if (nx < 0 or nx >= H) continue;
				if (ny < 0 or ny >= W) continue;
				G[now].push_back(cast(nx, ny));	
			}
			continue;
		}
		int nx = i;int ny = j;
		if (S[i][j] == 'L') {
			ny--;
		} else if (S[i][j] == 'R') {
			ny++;
		} else if (S[i][j] == 'D') {
			nx++;
		} else {
			nx--;
		}
		if (nx < 0 or nx >= H) continue;
		if (ny < 0 or ny >= W) continue;
		G[now].push_back(cast(nx, ny));
	}
	Graph G1(H * W);
	for (int v = 0;v < H * W;v++) for (auto nv : G[v]) G1[nv].push_back(v);
	vector<int> dist(H *W, -1), dist1(H *W, -1);
	BFS(G, dist, st);BFS(G1, dist1, gl);
	int ans = dist[gl];
	for (int i = 0;i < H;i++) for (int j = 0;j < W;j++) {
		if (S[i][j] == '#') continue;
		int now = cast(i, j);
		if (S[i][j] == 'S' || S[i][j] == 'G' || S[i][j] == '.') continue;
		if (dist[now] == -1) continue;
		for (auto vc : vecs) {
			int nx = i + vc.first;int ny = j + vc.second;
			if (nx < 0 or nx >=H) continue;
			if (ny < 0 or ny >= W) continue;
			int nv = cast(nx, ny);
			if (dist1[nv] == -1) continue;
			if (ans == -1) {
				ans = dist[now] + 1 + dist1[nv];
			} else {
				ans = min(ans, dist[now] + 1 + dist1[nv]);
			}
		}
	}
	cout << ans << endl;
}
accuracy: 1
time_ms: 10
memory_kb: 13780
final_rank: 18