#include using namespace std; #define FOR(i,n) for(int i = 0; i < (n); i++) #define sz(c) ((int)c.size()) #define ten(n) ((int)1e##n) using ll = long long; int n, m; bool in(int x, int y) { return x >= 0 && x < n && y >= 0 && y < m; } int dx1[] = { 2, 2, 1, 1, -1, -1, -2, -2 }; int dy1[] = { -1, 1, -2, 2, -2, 2, -1, 1 }; int dx2[] = { 1, 1, -1, -1 }; int dy2[] = { 1, -1, 1, -1 }; char t[500][501]; int memo[500][500][2]; int main() { cin >> n >> m; FOR(i, n) cin >> t[i]; int sx, sy, gx, gy; FOR(i, n) FOR(j, m) { if (t[i][j] == 'S') sx = i, sy = j; if (t[i][j] == 'G') gx = i, gy = j; } memset(memo, 0x2f, sizeof(memo)); memo[sx][sy][0] = 0; queue> q; q.emplace(sx, sy, 0); while (!q.empty()) { int x, y, c; tie(x, y, c) = q.front(); q.pop(); int kmax = (c == 0) ? 8 : 4; auto dx = (c == 0) ? dx1 : dx2; auto dy = (c == 0) ? dy1 : dy2; FOR(k, kmax) { int nx = x + dx[k], ny = y + dy[k]; if (!in(nx, ny)) continue; int nc = c; if (t[nx][ny] == 'R') nc ^= 1; if (memo[nx][ny][nc] > memo[x][y][c] + 1) { memo[nx][ny][nc] = memo[x][y][c] + 1;; q.emplace(nx, ny, nc); } } } int ans = min(memo[gx][gy][0], memo[gx][gy][1]); if (ans > ten(5)) ans = -1; cout << ans << endl; return 0; }