#include typedef long long LL; #define SORT(c) sort((c).begin(),(c).end()) #define FOR(i,a,b) for(int i=(a);i<(b);++i) #define REP(i,n) FOR(i,0,n) using namespace std; int cost[512][512][2]; int h,w; vector fi; int main(void) { cin >> h >> w; REP(i,h) REP(j,w) REP(k,2) cost[i][j][k]=-1048576; int dx[12]={1,1,-1,-1,1,1,2,2,-1,-1,-2,-2}; int dy[12]={1,-1,-1,1,2,-2,1,-1,2,-2,1,-1}; fi.resize(h); REP(i,h) cin >> fi[i]; priority_queue > dijk; REP(i,h) REP(j,w) if(fi[i][j]=='S') dijk.push(make_tuple(0,i,j,0)); // negcos,x,y,type; while(!dijk.empty()){ int negc,x,y,t; tie(negc,x,y,t)=dijk.top(); dijk.pop(); if(x<0||h<=x||y<0||w<=y) continue; if(cost[x][y][t]>=negc) continue; cost[x][y][t]=negc; if(fi[x][y]=='R') t=1-t; if(t) REP(i,4) dijk.push(make_tuple(negc-1,x+dx[i],y+dy[i],t)); else REP(i,8) dijk.push(make_tuple(negc-1,x+dx[i+4],y+dy[i+4],t)); } int answer; REP(i,h) REP(j,w) if(fi[i][j]=='G') answer=-max(cost[i][j][0],cost[i][j][1]); if(answer>1048000) cout << -1 << endl; else cout << answer << endl; return 0; }