#include #include #include #include using namespace std; #define RREP(i,s,e) for (i = s; i >= e; i--) #define rrep(i,n) RREP(i,n-1,0) #define REP(i,s,e) for (i = s; i < e; i++) #define rep(i,n) REP(i,0,n) #define INF 100000000 typedef long long ll; int main() { int i, j, k, l, h, w; int dis[2][500][500]; string s[500]; cin >> h >> w; rep (i,h) cin >> s[i]; rep (i,2) rep (j,h) rep (k,w) dis[i][j][k] = INF; rep (i,h) rep (j,w) if (s[i][j] == 'S') { queue> q; int kn[8] = {2,1,2,-1,-2,1,-2,-1}; dis[1][i][j] = 0; q.push(make_tuple(i,j,true)); while (!q.empty()) { int x, y, d; bool knight; tie(x,y,knight) = q.front(); q.pop(); if (s[x][y] == 'G') { cout << dis[knight][x][y] << endl; return 0; } d = dis[knight][x][y]; knight ^= s[x][y] == 'R'; if (knight) { rep (k,8) { int nx = x+kn[k]; int ny = y+kn[(k+1)%8]; if (nx >= 0 && nx < h && ny >= 0 && ny < w && dis[knight][nx][ny] > d+1) { dis[knight][nx][ny] = d+1; q.push(make_tuple(nx,ny,knight)); } } } else { for (k = -1; k <= 1; k+=2) { for (l = -1; l <= 1; l+=2) { int nx = x+k; int ny = y+l; if (nx >= 0 && nx < h && ny >= 0 && ny < w && dis[knight][nx][ny] > d+1) { dis[knight][nx][ny] = d+1; q.push(make_tuple(nx,ny,knight)); } } } } } } cout << -1 << endl; return 0; }