# include using namespace std; typedef long long ll; // # define int long long # define lc u << 1 # define rc u << 1 | 1 # define fi first # define se second const int N = 505; int n, m; char mp[N][N]; struct node { int x, y, op; }; int dis[N][N][2]; int dx1[8] = {1, 2, 1, 2, -1, -2, -1, -2}, dy1[8] = {2, 1, -2, -1, 2, 1, -2, -1}; int dx2[4] = {1, 1, -1, -1}, dy2[4] = {1, -1, 1, -1}; queue q; signed main () { scanf ("%d%d", &n, &m); for (int i = 1; i <= n; i ++ ) { for (int j = 1; j <= m; j ++ ) scanf (" %c", &mp[i][j]); } int sx = 0, sy = 0, ex = 0, ey = 0; for (int i = 1; i <= n; i ++ ) { for (int j = 1; j <= m; j ++ ) { if (mp[i][j] == 'S') sx = i, sy = j; else if (mp[i][j] == 'G') ex = i, ey = j; } } memset (dis, 0x3f, sizeof dis); dis[sx][sy][0] = 0; q.push ({sx, sy, 0}); while (!q.empty ()) { int x = q.front ().x, y = q.front ().y, op = q.front ().op; q.pop (); if (op == 0) { for (int i = 0; i < 8; i ++ ) { int nx = x + dx1[i], ny = y + dy1[i]; if (nx < 1 || nx > n || ny < 1 || ny > m) continue; int nop = op ^ (mp[nx][ny] == 'R'); if (dis[nx][ny][nop] > dis[x][y][op] + 1) { dis[nx][ny][nop] = dis[x][y][op] + 1; q.push ({nx, ny, nop}); } } } else { for (int i = 0; i < 4; i ++ ) { int nx = x + dx2[i], ny = y + dy2[i]; if (nx < 1 || nx > n || ny < 1 || ny > m) continue; int nop = op ^ (mp[nx][ny] == 'R'); if (dis[nx][ny][nop] > dis[x][y][op] + 1) { dis[nx][ny][nop] = dis[x][y][op] + 1; q.push ({nx, ny, nop}); } } } } int ans = min (dis[ex][ey][0], dis[ex][ey][1]); if (ans == 0x3f3f3f3f) ans = -1; printf ("%d\n", ans); return 0; }