#include using namespace std; string g[500]; int dist[500][500][2]; vector dy[2] = { {1, 2, 2, 1, -1, -2, -2, -1}, {1, 1, -1, -1}, }; vector dx[2] = { {2, 1, -1, -2, -2, -1, 1, 2}, {1, -1, -1, 1}, }; int main() { int h, w; int sy, sx, gy, gx; cin >> h >> w; for (int i = 0; i < h; i++) { cin >> g[i]; for (int j = 0; j < w; j++) { if (g[i][j] == 'S') sy = i, sx = j; if (g[i][j] == 'G') gy = i, gx = j; } } memset(dist, -1, sizeof(dist)); dist[sy][sx][0] = 0; queue> q; q.emplace(sy, sx, 0); while (!q.empty()) { int y, x, t; tie(y, x, t) = q.front(); q.pop(); for (int k = 0; k < dy[t].size(); k++) { int ny = y + dy[t][k]; int nx = x + dx[t][k]; if (ny < 0 || nx < 0 || ny >= h || nx >= w) continue; int nt = g[ny][nx] == 'R' ? !t : t; if (dist[ny][nx][nt] != -1) continue; dist[ny][nx][nt] = dist[y][x][t] + 1; q.emplace(ny, nx, nt); } } if (dist[gy][gx][0] == -1) dist[gy][gx][0] = 1e9; if (dist[gy][gx][1] == -1) dist[gy][gx][1] = 1e9; int ans = min(dist[gy][gx][0], dist[gy][gx][1]); if (ans == 1e9) ans = -1; cout << ans << endl; }