#include #define FOR(i,a,b) for(int i=(a);i<(b);++i) #define REP(i,n) FOR(i,0,n) using namespace std; int f[512][512][2]; int h, w, c, x, y, t, a; vector s; priority_queue> q; 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}; int main(void) { cin >> h >> w; REP(i,h) REP(j,w) REP(k,2) f[i][j][k]=-1048576; s.resize(h); REP(i,h) cin >> s[i]; REP(i,h) REP(j,w) if(s[i][j]== 'S') q.push(make_tuple(0,i,j,0)); while(!q.empty()){ tie(c,x,y,t)=q.top(); q.pop(); if(x<0||h<=x||y<0||w<=y) continue; if(f[x][y][t]>=c) continue; f[x][y][t]=c; if(s[x][y]== 'R') t=1-t; if(t) REP(i,4) q.push(make_tuple(c-1,x+dx[i],y+dy[i],t)); else REP(i,8) q.push(make_tuple(c-1,x+dx[i+4],y+dy[i+4],t)); } REP(i,h) REP(j,w) if(s[i][j]== 'G') a=-max(f[i][j][0],f[i][j][1]); if(a>1048000) cout << -1 << endl; else cout << a << endl; return 0; }