#include using namespace std; #define rep(i,n) for(ll i=0;i=0;i--) #define perl(i,r,l) for(ll i=r-1;i>=l;i--) #define fi first #define se second #define pb push_back #define ins insert #define pqueue(x) priority_queue,greater> #define all(x) (x).begin(),(x).end() #define CST(x) cout<> #define rev(x) reverse(x); using ll=long long; using vl=vector; using vvl=vector>; using pl=pair; using vpl=vector; using vvpl=vector; const ll MOD=1000000007; const ll MOD9=998244353; const int inf=1e9+10; const ll INF=4e18; //const ll dy[9]={0,1,-1,0,1,1,-1,-1,0}; //const ll dx[9]={1,0,0,-1,1,-1,1,-1,0}; template inline bool chmin(T& a, T b) { if (a > b) { a = b; return true; } return false; } template inline bool chmax(T& a, T b) { if (a < b) { a = b; return true; } return false; } int main(){ ll h,w;cin >> h >> w; vector g(h); rep(i,h)cin >> g[i]; vl dx={1,2,2,1,-1,-2,-2,-1}; vl dy={2,1,-1,-2,-2,-1,1,2}; vl ddx={1,1,-1,-1}; vl ddy={1,-1,-1,1}; ll sx,sy,gx,gy; rep(i,h)rep(j,w){ if(g[i][j]=='S'){ sx=i,sy=j;g[i][j]='.'; } if(g[i][j]=='G'){ gx=i,gy=j;g[i][j]='.'; } } ll dist[h][w][2]; rep(i,h)rep(j,w)rep(k,2)dist[i][j][k]=INF; dist[sx][sy][0]=0; queue que;que.push(sx*w*2+sy*2); while(!que.empty()){ ll v=que.front();que.pop(); ll p=v%2;v/=2; if(p==0){ rep(i,8){ ll nx=v/w+dx[i],ny=v%w+dy[i]; if(nx<0||ny<0||nx>=h||ny>=w)continue; ll to=p;if(g[nx][ny]=='R')to^=1; if(dist[nx][ny][to]!=INF)continue; dist[nx][ny][to]=dist[v/w][v%w][p]+1; que.push(nx*w*2+ny*2+to); } } else{ rep(i,4){ ll nx=v/w+ddx[i],ny=v%w+ddy[i]; if(nx<0||ny<0||nx>=h||ny>=w)continue; ll to=p;if(g[nx][ny]=='R')to^=1; if(dist[nx][ny][to]!=INF)continue; dist[nx][ny][to]=dist[v/w][v%w][p]+1; que.push(nx*w*2+ny*2+to); } } } ll ans=min(dist[gx][gy][0],dist[gx][gy][1]); if(ans==INF)cout << -1 << endl; else cout << ans << endl; }