#include using namespace std; #define FOR(i,a,b) for(int i=(a);i<(b);i++) #define REP(i,n) FOR(i,0,n) #define ALL(v) (v).begin(),(v).end() template inline bool chmax(A &a, B b) { if (a inline bool chmin(A &a, B b) { if (a>b) { a=b; return 1; } return 0; } typedef unsigned long long ull; typedef long long ll; typedef pair pii; typedef pair pll; typedef pair P; const ll INF = 1ll<<29; const ll MOD = 1000000007; const double EPS = 1e-10; int h, w; string maps[500]; int dp[500][500][2]; int c[2] = {8, 4}; int dx[2][8] = {{2,2,1,-1,-2,-2,-1,1}, {1,1,-1,-1}}; int dy[2][8] = {{1,-1,-2,-2,-1,1,2,2}, {1,-1,-1,1}}; int main() { cin >> h >> w; REP(i, h) cin >> maps[i]; pii sp, ep; REP(i, h) REP(j, w) { if (maps[i][j] == 'S') sp = pii(i, j); if (maps[i][j] == 'G') ep = pii(i, j); } fill(dp[0][0], dp[h][0], INF); queue

que; dp[sp.first][sp.second][0] = 0; que.push(P(0, sp)); while (!que.empty()) { int s = que.front().first; int x = que.front().second.second; int y = que.front().second.first; que.pop(); REP(i, c[s]) { int nx = x + dx[s][i]; int ny = y + dy[s][i]; if (!(nx >= 0 && nx < w && ny >= 0 && ny < h)) continue; int ns = s ^ (maps[ny][nx] == 'R'); if (chmin(dp[ny][nx][ns], dp[y][x][s] + 1)) que.push(P(ns, pii(ny, nx))); } } int ans = INF; REP(i, 2) chmin(ans, dp[ep.first][ep.second][i]); if (ans == INF) ans = -1; cout << ans << endl; return 0; }