#include using namespace std; typedef long long ll; typedef unsigned long long ull; typedef long double ld; typedef pair P; #define EACH(i,a) for (auto& i : a) #define FOR(i,a,b) for (ll i=(a);i<(b);i++) #define RFOR(i,a,b) for (ll i=(b)-1;i>=(a);i--) #define REP(i,n) for (ll i=0;i<(n);i++) #define RREP(i,n) for (ll i=(n)-1;i>=0;i--) #define debug(x) cout<<#x<<": "< istream& operator>>(istream& is, vector& vec) { EACH(x,vec) is >> x; return is; } /* template ostream& operator<<(ostream& os, tuple& t) { for (size_t i = 0; i < tuple_size< tuple >::value; ++i) { if (i) os << " "; os << get<0>(t); } return os; } */ template ostream& operator<<(ostream& os, vector& vec) { REP(i,vec.size()) { if (i) os << " "; os << vec[i]; } return os; } template ostream& operator<<(ostream& os, vector< vector >& vec) { REP(i,vec.size()) { if (i) os << endl; os << vec[i]; } return os; } struct Node { int x, y, mode, cost; }; bool operator>(const Node& n1, const Node& n2) { return n1.cost > n2.cost; } int H, W; vector m; bool inRange(int x, int y) { return 0 <= x && x < W && 0 <= y && y < H; } vector< vector

> nxt = { {{1, 2}, {2, 1}, {1, -2}, {2, -1}, {-1, 2}, {-2, 1}, {-1, -2}, {-2, -1}}, {{1, 1}, {1, -1}, {-1, 1}, {-1, -1}}, }; int main() { std::ios::sync_with_stdio(false); std::cin.tie(0); cin >> H >> W; m.resize(H); cin >> m; int sx, sy, gx, gy; REP(y, H) REP(x, W) { if (m[y][x] == 'S') { m[y][x] = '.'; sx = x, sy = y; } else if (m[y][x] == 'G') { m[y][x] = '.'; gx = x, gy = y; } } vector< vector< vector > > dist(H, vector< vector >(W, vector(2, inf))); priority_queue, greater > Q; Q.push({sx, sy, 0, 0}); while ( !Q.empty() ) { Node node = Q.top(); Q.pop(); int x = node.x, y = node.y, cost = node.cost, mode = node.mode; // cout << x << " " << y << " " << mode << " " << cost << endl; if (cost > dist[y][x][mode]) continue; REP(i, nxt[mode].size()) { int nx = x + nxt[mode][i].first; int ny = y + nxt[mode][i].second; if ( !inRange(nx, ny) ) continue; int nm = m[ny][nx] == 'R' ? !mode : mode; if ( cost+1 < dist[ny][nx][nm] ) { dist[ny][nx][nm] = cost+1; Q.push({nx, ny, nm, dist[ny][nx][nm]}); } } } int ans = inf; REP(i, 2) ans = min(ans, dist[gy][gx][i]); if (ans == inf) cout << -1 << endl; else cout << ans << endl; }