#define _USE_MATH_DEFINES #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; typedef long long ll; typedef unsigned long long ull; typedef pair i_i; typedef pair ll_i; typedef pair d_i; typedef pair ll_ll; typedef pair d_d; struct edge { int u, v; ll w; }; ll MOD = 1000000007; ll _MOD = 1000000009; double EPS = 1e-10; int dy[2][8] = {{-1, -2, -2, -1, 1, 2, 2, 1}, {-1, -1, 1, 1, -1, -1, 1, 1}}; int dx[2][8] = {{-2, -1, 1, 2, 2, 1, -1, -2}, {-1, 1, 1, -1, -1, 1, 1, -1}}; int H, W; int f(int y, int x, int t) { return (y * W + x) * 2 + t; } int main() { cin >> H >> W; vector a(H); int sy, sx, ty, tx; 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, a[y][x] = '.'; if (a[y][x] == 'G') ty = y, tx = x, a[y][x] = '.'; } } vector > > d(H, vector >(W, vector(2, INT_MAX))); d[sy][sx][0] = 0; queue q; q.push(f(sy, sx, 0)); while (!q.empty()) { int z = q.front(); q.pop(); int y = z / 2 / W, x = z / 2 % W, t = z % 2; for (int k = 0; k < 8; k++) { int _y = y + dy[t][k], _x = x + dx[t][k]; if (_y >= 0 && _y < H && _x >= 0 && _x < W) { int _t = t; if (a[_y][_x] == 'R') _t ^= 1; if (d[_y][_x][_t] > d[y][x][t] + 1) { d[_y][_x][_t] = d[y][x][t] + 1; q.push(f(_y, _x, _t)); } } } } int ans = min(d[ty][tx][0], d[ty][tx][1]); if (ans == INT_MAX) ans = -1; cout << ans << endl; }