#include using namespace std; using ll = long long; int main() { ios::sync_with_stdio(false); cin.tie(0); int h, w, sy, sx, gy, gx; cin >> h >> w; vector A(h); for(int y = 0; y < h; y++){ cin >> A[y]; for(int x = 0; x < w; x++){ if(A[y][x] == 'S') sy = y, sx = x; if(A[y][x] == 'G') gy = y, gx = x; } } vector>> dir = { {{-1, -2}, {-1, 2}, {1, -2}, {1, 2}, {2, 1}, {2, -1}, {-2, -1}, {-2, 1}}, {{1, 1}, {1, -1}, {-1, 1}, {-1, -1}} }; queue> nxt; vector>> dp(h, vector>(w, array({1 << 30, 1 << 30}))); dp[sy][sx][0] = 0; nxt.emplace(sy, sx, 0); while(!nxt.empty()){ int y, x, s, dy, dx, ny, nx, ns; tie(y, x, s) = nxt.front(); nxt.pop(); for(auto &&p : dir[s]){ tie(dy, dx) = p; ny = y + dy; nx = x + dx; if(ny < 0 || ny >= h || nx < 0 || nx >= w) continue; ns = s ^ (A[ny][nx] == 'R'); if(dp[y][x][s] + 1 >= dp[ny][nx][ns]) continue; dp[ny][nx][ns] = dp[y][x][s] + 1; nxt.emplace(ny, nx, ns); } } int ans = min(dp[gy][gx][0], dp[gy][gx][1]); if(ans == (1 << 30)) ans = -1; cout << ans << '\n'; }