#include #define _overload(_1,_2,_3,name,...) name #define _rep(i,n) _range(i,0,n) #define _range(i,a,b) for(int i=int(a);i=int(b);--i) #define rrep(...) _overload(__VA_ARGS__,_rrange,_rrep,)(__VA_ARGS__) #define _all(arg) begin(arg),end(arg) #define uniq(arg) sort(_all(arg)),(arg).erase(unique(_all(arg)),end(arg)) #define getidx(ary,key) lower_bound(_all(ary),key)-begin(ary) #define clr(a,b) memset((a),(b),sizeof(a)) #define bit(n) (1LL<<(n)) #define popcount(n) (__builtin_popcountll(n)) templatebool chmax(T &a, const T &b) { return (abool chmin(T &a, const T &b) { return (b; int main(void){ int h,w; cin >> h >> w; rep(i,h) cin >> board[i]; clr(dist,-1); int sh,sw,gh,gw; rep(i,h)rep(j,w){ if(board[i][j]=='S') sh=i,sw=j; if(board[i][j]=='G') gh=i,gw=j; } dist[sh][sw][0]=0; queue q; q.push(state(sh,sw,0)); while(!q.empty()){ int ch,cw,type; tie(ch,cw,type)=q.front();q.pop(); if(type==0){ const int dh[8]={-2,-2,-1,-1,1,1,2,2}; const int dw[8]={-1,1,-2,2,-2,2,-1,1}; rep(i,8){ int nh=ch+dh[i],nw=cw+dw[i],ntype=type; if(nh<0||h<=nh) continue; if(nw<0||w<=nw) continue; if(board[nh][nw]=='R') ntype^=1; if(dist[nh][nw][ntype]==-1){ dist[nh][nw][ntype]=dist[ch][cw][type]+1; q.push(state(nh,nw,ntype)); } } }else{ const int dh[4]={-1,-1,1,1}; const int dw[4]={-1,1,-1,1}; rep(i,4){ int nh=ch+dh[i],nw=cw+dw[i],ntype=type; if(nh<0||h<=nh) continue; if(nw<0||w<=nw) continue; if(board[nh][nw]=='R') ntype^=1; if(dist[nh][nw][ntype]==-1){ dist[nh][nw][ntype]=dist[ch][cw][type]+1; q.push(state(nh,nw,ntype)); } } } } int ans=1<<20; rep(i,2) if(dist[gh][gw][i]!=-1) chmin(ans,dist[gh][gw][i]); if(ans==(1<<20)) ans=-1; cout << ans << endl; return 0; }