#include #include using namespace std; #define INF 100000000 int h,w,sx,sy,gx,gy,dx4[] = {1,1,-1,-1},dy4[] = {1,-1,-1,1},dx8[] = {2,2,1,1,-1,-1,-2,-2},dy8[] = {1,-1,2,-2,2,-2,1,-1},d[500][500][2]; char board[500][500]; int bfs(){ queue>> q; q.push(make_pair(1,pair(sx,sy))); d[sx][sy][1] = 0; while(!q.empty()){ int mode = q.front().first; pair p = q.front().second; q.pop(); if(p.first == gx && p.second == gy) break; if(mode){ for(int i = 0;i < 8;i++){ int nx = p.first + dx8[i],ny = p.second + dy8[i],nm = mode ^ (board[nx][ny] == 'R'); if(nx >= 0 && nx < h && ny >= 0 && ny < w && d[nx][ny][nm] == INF){ q.push(make_pair(nm,pair(nx,ny))); d[nx][ny][nm] = d[p.first][p.second][mode] + 1; } } }else{ for(int i = 0;i < 4;i++){ int nx = p.first + dx4[i],ny = p.second + dy4[i],nm = mode ^ (board[nx][ny] == 'R'); if(nx >= 0 && nx < h && ny >= 0 && ny < w && d[nx][ny][nm] == INF){ q.push(make_pair(nm,pair(nx,ny))); d[nx][ny][nm] = d[p.first][p.second][mode] + 1; } } } } return min(d[gx][gy][0],d[gx][gy][1]); } int main(){ cin >> h >> w; for(int i = 0;i < h;i++){ string s; cin >> s; for(int j = 0;j < w;j++){ board[i][j] = s[j]; if(board[i][j] == 'S'){ sx = i; sy = j; }else if(board[i][j] == 'G'){ gx = i; gy = j; } } } for(int i = 0;i < h;i++) for(int j = 0;j < w;j++) d[i][j][0] = d[i][j][1] = INF; int ans = bfs(); if(ans == INF) ans = -1; cout << ans << endl; }