#include #include #include #include #include #include #include #include #include #include static const int MOD = 1000000007; using ll = long long; using namespace std; template constexpr T INF = ::numeric_limits::max()/32*15+208; template vector make_v(U size, const T& init){ return vector(static_cast(size), init); } template auto make_v(U size, Ts... rest) { return vector(static_cast(size), make_v(rest...)); } template void chmin(T &a, const T &b){ a = (a < b ? a : b); } template void chmax(T &a, const T &b){ a = (a > b ? a : b); } int main() { int h, w; cin >> h >> w; vector v(h); int sy = 0, sx = 0, gy = 0, gx = 0; for (int i = 0; i < h; ++i) { cin >> v[i]; for (int j = 0; j < w; ++j) { if(v[i][j] == 'S') sy = i, sx = j; if(v[i][j] == 'G') gy = i, gx = j; } } array dy1{1, 2, 2, 1, -1, -2, -2, -1}, dx1{-2, -1, 1, 2, 2, 1, -1, -2}; array dy2{1, 1, -1, -1}, dx2{1, -1, 1, -1}; queue> Q; Q.emplace(0, sy, sx); auto d = make_v(2, h, w, INF); auto in = [&](int y, int x){ return 0 <= y && y < h && 0 <= x && x < w; }; d[0][sy][sx] = 0; while(!Q.empty()){ int a, y, x; tie(a, y, x) = Q.front(); Q.pop(); if(!a){ for (int k = 0; k < 8; ++k) { if(in(y+dy1[k], x+dx1[k]) && d[a^(v[y+dy1[k]][x+dx1[k]] == 'R')][y+dy1[k]][x+dx1[k]] == INF){ int b = a^(v[y+dy1[k]][x+dx1[k]] == 'R'); d[b][y+dy1[k]][x+dx1[k]] = d[a][y][x] + 1; Q.emplace(b, y+dy1[k], x+dx1[k]); } } }else { for (int k = 0; k < 4; ++k) { if(in(y+dy2[k], x+dx2[k]) && d[a^(v[y+dy2[k]][x+dx2[k]] == 'R')][y+dy2[k]][x+dx2[k]] == INF){ int b = a^(v[y+dy2[k]][x+dx2[k]] == 'R'); d[b][y+dy2[k]][x+dx2[k]] = d[a][y][x] + 1; Q.emplace(b, y+dy2[k], x+dx2[k]); } } } } int ans = min(d[0][gy][gx], d[1][gy][gx]); if(ans == INF) puts("-1"); else cout << ans << "\n"; return 0; }