#include #include #include #include #include #include #include using namespace std; #define FOR(i,a,b) for (int i=(a);i<(b);i++) #define FORR(i,a,b) for (int i=(b)-1;i>=(a);i--) #define REP(i,n) for (int i=0;i<(n);i++) #define RREP(i,n) for (int i=(n)-1;i>=0;i--) #define pb push_back #define ALL(a) (a).begin(),(a).end() #define PI 3.1415926535 typedef long long ll; typedef pair P; const int INF = 99999999; const int MAX_H = 500; const int MAX_W = 500; int H, W; // 'S'(開始位置), 'G'(目標位置), 'R'(赤いマス), '.'(ただのマス)のいずれか // 'S', 'G' は普通のマスであることが保証されている // 駒は最初はナイト // 赤いマスに乗ったとき、ナイトならミニビショップに、ミニビショップならナイトに変わる char maze[MAX_H][MAX_W]; // 1=knight, 0=mini-bishop int d[MAX_H][MAX_W][2]; int sx, sy, gx, gy; // knight int dx8[8] = {2, 2, 1, 1, -1, -1, -2, -2}; int dy8[8] = {1, -1, 2, -2, 2, -2, 1, -1}; // mini-bishop int dx4[4] = {1, 1, -1, -1}; int dy4[4] = {1, -1, -1, 1}; void input() { cin >> H >> W; REP(i, H) { string s; cin >> s; REP(j, W) { maze[i][j] = s[j]; if (maze[i][j] == 'S') { sx = i; sy = j; } else if (maze[i][j] == 'G') { gx = i; gy = j; } } } } bool inside(int x, int y) { return x >= 0 && x < H && y >= 0 && y < W; } int bfs() { // 駒の種類(1=knight, 0=mini-bishop), 座標 queue> que; REP(i, H) REP(j, W) REP(k, 2) d[i][j][k] = INF; que.push(make_pair(1, P(sx, sy))); d[sx][sy][1] = 0; while (!que.empty()) { int mode = que.front().first; // 駒の種類 P p = que.front().second; // 座標 que.pop(); if (p.first == gx && p.second == gy) break; if (mode == 1) { // マスpからknightの利きで移動するとき REP(k, 8) { int nx = p.first + dx8[k], ny = p.second + dy8[k]; // 次のマスが赤だったら、次のマスでは駒が変わる int nm = mode ^ (maze[nx][ny] == 'R'); if (inside(nx, ny) && d[nx][ny][nm] == INF) { que.push(make_pair(nm, P(nx, ny))); d[nx][ny][nm] = d[p.first][p.second][mode] + 1; } } } else { // マスpからmini-bishopの利きで移動するとき REP(k, 4) { int nx = p.first + dx4[k], ny = p.second + dy4[k]; // 次のマスが赤だったら、次のマスでは駒が変わる int nm = mode ^ (maze[nx][ny] == 'R'); if (inside(nx, ny) && d[nx][ny][nm] == INF) { que.push(make_pair(nm, P(nx, ny))); d[nx][ny][nm] = d[p.first][p.second][mode] + 1; } } } } return min(d[gx][gy][0], d[gx][gy][1]); } void solve() { int ans = bfs(); if (ans == INF) ans = -1; cout << ans << endl; // REP(i, H) { // REP(j, W) { // if (d[i][j][0] != INF) { // cout << d[i][j][0] << ' '; // } else { // cout << 'x' << ' '; // } // } // cout << endl; // } // cout << endl; // // REP(i, H) { // REP(j, W) { // if (d[i][j][1] != INF) { // cout << d[i][j][1] << ' '; // } else { // cout << 'x' << ' '; // } // } // cout << endl; // } } int main() { input(); solve(); }