#include #define Add(x,y) (x+y>=mod)?(x+y-mod):(x+y) #define lowbit(x) x&(-x) #define pi pair #define pii pair> #define iip pair,ll> #define ppii pair,pair> #define fi first #define se second #define full(l,r,x) for(auto it=l;it!=r;it++) (*it)=x #define Full(a) memset(a,0,sizeof(a)) #define open(s1,s2) freopen(s1,"r",stdin),freopen(s2,"w",stdout); #define For(i,l,r) for(int i=l;i<=r;i++) #define _For(i,l,r) for(int i=r;i>=l;i--) using namespace std; typedef double db; typedef unsigned long long ull; typedef int ll; bool Begin; const ll N=505; inline ll read(){ ll x=0,f=1; char c=getchar(); while(c<'0'||c>'9'){ if(c=='-') f=-1; c=getchar(); } while(c>='0'&&c<='9'){ x=(x<<1)+(x<<3)+(c^48); c=getchar(); } return x*f; } inline void write(ll x){ if(x<0){ putchar('-'); x=-x; } if(x>9) write(x/10); putchar(x%10+'0'); } inline char get(){ char c; while(1){ c=getchar(); if(c=='S'||c=='G'||c=='R'||c=='.') break; } return c; } struct Node{ ll x,y; bool F; }; char c; ll n,m,sx,sy,tx,ty,ans; ll dx1[]={1,1,2,2,-1,-1,-2,-2},dy1[]={-2,2,-1,1,-2,2,-1,1}; ll dx2[]={1,-1,1,-1},dy2[]={-1,1,1,-1}; ll dis[N][N][2]; bool f[N][N]; queue Q; void bfs(){ dis[sx][sy][0]=0; Q.push({sx,sy,0}); while(!Q.empty()){ ll x=Q.front().x,y=Q.front().y; bool F=Q.front().F,nF; Q.pop(); if(F){ for(int i=0;i<4;i++){ ll zx=x+dx2[i],zy=y+dy2[i]; if(zx<1||zx>n||zy<1||zy>m) continue; if(f[zx][zy]) nF=F^1ll; else nF=F; if(dis[zx][zy][nF]>dis[x][y][F]+1){ dis[zx][zy][nF]=dis[x][y][F]+1; Q.push({zx,zy,nF}); } } } else{ for(int i=0;i<8;i++){ ll zx=x+dx1[i],zy=y+dy1[i]; if(zx<1||zx>n||zy<1||zy>m) continue; if(f[zx][zy]) nF=F^1ll; else nF=F; if(dis[zx][zy][nF]>dis[x][y][F]+1){ dis[zx][zy][nF]=dis[x][y][F]+1; Q.push({zx,zy,nF}); } } } } } bool End; int main(){ n=read(),m=read(); for(int i=1;i<=n;i++){ for(int j=1;j<=m;j++){ char c=get(); if(c=='S') sx=i,sy=j; else if(c=='G') tx=i,ty=j; else if(c=='R') f[i][j]=1; dis[i][j][0]=dis[i][j][1]=1e9; } } bfs(); ans=min(dis[tx][ty][0],dis[tx][ty][1]); write(ans==1e9?-1:ans); //cerr<<'\n'<