#include #include #include #include #include #include #include #include #include #include #include #include #include #define repd(i,a,b) for (int i=(int)(a);i<(int)(b);i++) #define rep(i,n) repd(i,0,n) #define all(x) (x).begin(),(x).end() #define mod 1000000007 #define inf 2000000007 #define mp make_pair #define pb push_back typedef long long ll; using namespace std; template inline void output(T a, int p) { if(p) cout << fixed << setprecision(p) << a << "\n"; else cout << a << "\n"; } // end of template int nx[8] = {2, 2, 1, 1, -1, -1, -2, -2}; int ny[8] = {1, -1, 2, -2, 2, -2, 1, -1}; int bx[4] = {1, 1, -1, -1}; int by[4] = {1, -1, 1, -1}; int main() { cin.tie(0); ios::sync_with_stdio(0); // source code int H, W; cin >> H >> W; vector S(H); rep(i, H) cin >> S[i]; pair start, goal; rep(i, H) rep(j, W) { if (S[i][j] == 'S') start = mp(i, j); if (S[i][j] == 'G') goal = mp(i, j); } vector> visN(H, vector(W, -1)), visB(H, vector(W, -1)); queue, int>> q; // 0: knight, 1: bishop q.push(mp(start, 0)); visN[start.first][start.second] = 0; while (!q.empty()) { auto f = q.front(); int y = f.first.first; int x = f.first.second; int s = f.second; q.pop(); if (s == 0) { // knight int cnt = visN[y][x]; rep(k, 8) { if (x + nx[k] >= 0 && x + nx[k] < W && y + ny[k] >= 0 && y + ny[k] < H) { if(S[x + nx[k]][y + ny[k]] == 'R' && visB[y + ny[k]][x + nx[k]] == -1) { q.push(mp(mp(y + ny[k], x + nx[k]), 1)); visB[y + ny[k]][x + nx[k]] = cnt + 1; // cout << y + ny[k] << ", " << x + nx[k] << ": " << cnt + 1 << ": " << 1 << endl; } if(S[x + nx[k]][y + ny[k]] != 'R' && visN[y + ny[k]][x + nx[k]] == -1) { q.push(mp(mp(y + ny[k], x + nx[k]), 0)); visN[y + ny[k]][x + nx[k]] = cnt + 1; // cout << y + ny[k] << ", " << x + nx[k] << ": " << cnt + 1 << ": " << 0 << endl; } } } } if (s == 1) { int cnt = visB[y][x]; rep(k, 4) { if (x + bx[k] >= 0 && x + bx[k] < W && y + by[k] >= 0 && y + by[k] < H) { if(S[x + bx[k]][y + by[k]] == 'R' && visN[y + by[k]][x + bx[k]] == -1) { q.push(mp(mp(y + by[k], x + bx[k]), 0)); visN[y + by[k]][x + bx[k]] = cnt + 1; // cout << y + by[k] << ", " << x + bx[k] << ": " << cnt + 1 << ": " << 0 << endl; } if(S[x + bx[k]][y + by[k]] != 'R' && visB[y + by[k]][x + bx[k]] == -1) { q.push(mp(mp(y + by[k], x + bx[k]), 1)); visB[y + by[k]][x + bx[k]] = cnt + 1; // cout << y + by[k] << ", " << x + bx[k] << ": " << cnt + 1 << ": " << 1 << endl; } } } } } if(visN[goal.first][goal.second] == -1 && visB[goal.first][goal.second] == -1) { output(-1, 0); return 0; } if(visN[goal.first][goal.second] == -1) visN[goal.first][goal.second] = 100000; if(visB[goal.first][goal.second] == -1) visB[goal.first][goal.second] = 100000; output(min(visN[goal.first][goal.second], visB[goal.first][goal.second]), 0); return 0; }