#include using namespace std; struct Move { int x, y, count, isknight; Move(int x, int y, int count, int isknight) : x(x), y(y), count(count), isknight(isknight) {} }; int h, w; bool judge_inside(int x, int y) { return x >= 0 && x < w && y >= 0 && y < h; } int dx[] = {2, 2, 1, 1, -1, -1, -2, -2}; int dy[] = {1, -1, 2, -2, 2, -2, 1, -1}; int dx2[] = {1, -1, -1, 1}; int dy2[] = {1, 1, -1, -1}; int main() { cin.tie(0); ios::sync_with_stdio(false); cin >> h >> w; bool memo[500][500][2]; vector str(h); for (int i = 0; i < h; i++) cin >> str[i]; int sx, sy, gx, gy; for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) { if (str[i][j] == 'S') { sy = i; sx = j; } else if (str[i][j] == 'G') { gy = i; gx = j; } for (int k = 0; k < 2; k++) memo[i][j][k] = false; } } queue q; q.push(Move(sx, sy, 0, 1)); int ans = -1; while(!q.empty()) { Move m = q.front(); q.pop(); if (m.x == gx && m.y == gy) { ans = m.count; break; } if (memo[m.y][m.x][m.isknight]) continue; memo[m.y][m.x][m.isknight] = true; if (str[m.y][m.x] == 'R') m.isknight ^= 1; if (m.isknight) { for (int i = 0; i < 8; i++) { if (!judge_inside(m.x + dx[i], m.y + dy[i])) continue; q.push(Move(m.x + dx[i], m.y + dy[i], m.count + 1, 1)); } } else { for (int i = 0; i < 4; i++) { if (!judge_inside(m.x + dx2[i], m.y + dy2[i])) continue; q.push(Move(m.x + dx2[i], m.y + dy2[i], m.count + 1, 0)); } } } cout << ans << "\n"; return 0; }