#include #include using namespace std; using namespace atcoder; typedef long long ll; typedef long double ld; #define REP(i, n) for (int i = 0; i < (n); ++i) #define REPR(i, n) for (int i = n - 1; i >= 0; --i) #define FOR(i, m, n) for (int i = m; i < n; ++i) #define FORR(i, m, n) for (int i = m; i >= n; --i) #define ALL(v) (v).begin(),(v).end() #define ALLR(v) (v).rbegin(),(v).rend() #define fi first #define se second #define PB push_back #define EB emplace_back template using PQ = priority_queue; template using QP = priority_queue,greater>; templatevoid debug(const T &v,ll h,ll w){for(ll i=0;ivoid debug(const T &v,ll n){for(ll i=0;ivoid debug(const vector&v){debug(v,v.size());} templatevoid debug(const vector>&v){for(auto &vv:v)debug(vv,vv.size());} templatevoid debug(stack st){while(!st.empty()){cerr<void debug(queue st){while(!st.empty()){cerr<void debug(deque st){while(!st.empty()){cerr<void debug(PQ st){while(!st.empty()){cerr<void debug(QP st){while(!st.empty()){cerr<void debug(const set&v){for(auto z:v)cerr<void debug(const multiset&v){for(auto z:v)cerr<void debug(const array &a){for(auto z:a)cerr<void debug(const map&v){for(auto z:v)cerr<<"["<void foo(Head&& head, Tail&&... tail){cerr << head << " ";foo(move(tail)...);} templatebool chmax(T &a, const T &b) { if (abool chmin(T &a, const T &b) { if (b> h >> w; vector s(h); REP(i,h) cin >> s[i]; int sx,sy,gx,gy; REP(i,h) REP(j,w){ if(s[i][j]=='S') sx=i,sy=j; if(s[i][j]=='G') gx=i,gy=j; } vector d(h,vector(w,vector(2,inf))); d[sx][sy][0]=0; queue> q; q.push({sx,sy,0}); while(!q.empty()){ auto [u,v,t]=q.front();q.pop(); // foo(u,v,t); if(t==0){ REP(i,8){ int nx=u+dx[i],ny=v+dy[i]; if(nx<0||nx>=h||ny<0||ny>=w) continue; if(chmin(d[nx][ny][s[nx][ny]=='R'],d[u][v][t]+1)){ q.push({nx,ny,s[nx][ny]=='R'}); } } } else{ REP(i,4){ int nx=u+x[i],ny=v+y[i]; if(nx<0||nx>=h||ny<0||ny>=w) continue; if(chmin(d[nx][ny][s[nx][ny]!='R'],d[u][v][t]+1)){ q.push({nx,ny,s[nx][ny]!='R'}); } } } } int ans=min(d[gx][gy][0],d[gx][gy][1]); cout << (ans==inf?-1:ans) << endl; }