#include using namespace std; #define int long long typedef pairpint; typedef vectorvint; typedef vectorvpint; #define pb push_back #define mp make_pair #define fi first #define se second #define all(v) (v).begin(),(v).end() #define rep(i,n) for(int i=0;i<(n);i++) #define reps(i,f,n) for(int i=(f);i<(n);i++) #define each(it,v) for(__typeof((v).begin()) it=(v).begin();it!=(v).end();it++) templateinline void chmin(T &t,U f){if(t>f)t=f;} templateinline void chmax(T &t,U f){if(t>H>>W; rep(i,H)cin>>fld[i]; rep(i,H)rep(j,W){ if(fld[i][j]=='S')sy=i,sx=j; if(fld[i][j]=='G')gy=i,gx=j; } fill_n(**dist,555*555*2,INF); dist[sy][sx][0]=0; queue>que; que.push(make_tuple(sy,sx,0)); while(que.size()){ int y,x,t; tie(y,x,t)=que.front(); que.pop(); rep(i,dx[t].size()){ int ny=y+dy[t][i]; int nx=x+dx[t][i]; if(ny<0||ny>=H||nx<0||nx>=W)continue; int nt=(t+(fld[ny][nx]=='R'))%2; if(dist[ny][nx][nt]!=INF)continue; dist[ny][nx][nt]=dist[y][x][t]+1; que.push(make_tuple(ny,nx,nt)); } } int cost=min(dist[gy][gx][0],dist[gy][gx][1]); if(cost==INF)cout<<-1<