#include #include #include #include #include #include #include #include using namespace std; typedef tuple TUP; const int INF = 1e9; void show(vector> &vv) { int h = vv.size(); int w = vv[0].size(); for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) { printf("%d ", vv[i][j] == INF ? 0 : vv[i][j]); } cout << endl; } cout << endl; } int main() { int h, w; cin >> h >> w; vector board; string str; int sx, sy; for (int i = 0; i < h; i++) { cin >> str; auto it = find(str.begin(), str.end(), 'S'); if (it != str.end()) { sy = i; sx = it - str.begin(); } board.emplace_back(str); } vector> knight, bishop; knight.assign(board.size(), vector(board[0].size(), INF)); knight[sy][sx] = 0; bishop = knight; int k_dx[8] = {2, 1, -1, -2, -2, -1, 1, 2}; int k_dy[8] = {1, 2, 2, 1, -1, -2, -2, -1}; int b_dx[4] = {1, -1, -1, 1}; int b_dy[4] = {1, 1, -1, -1}; queue que; que.push(make_tuple(sx * 1000 + sy, 0, 'k')); while (!que.empty()) { auto t = que.front(); que.pop(); int x = get<0>(t) / 1000; int y = get<0>(t) % 1000; int hands = get<1>(t); char c = get<2>(t); if (c == 'k') { for (int i = 0; i < 8; i++) { int nx = x + k_dx[i]; int ny = y + k_dy[i]; if (nx < 0 || w <= nx || ny < 0 || h <= ny) { continue; } if (knight[ny][nx] > hands + 1) { knight[ny][nx] = hands + 1; if (board[ny][nx] == 'G') { cout << hands + 1 << endl; // show(knight); // show(bishop); return 0; } que.push(make_tuple(nx * 1000 + ny, hands + 1, board[ny][nx] == 'R' ? 'b' : 'k')); } } } else { for (int i = 0; i < 4; i++) { int nx = x + b_dx[i]; int ny = y + b_dy[i]; if (nx < 0 || w <= nx || ny < 0 || h <= ny) { continue; } if (bishop[ny][nx] > hands + 1) { bishop[ny][nx] = hands + 1; if (board[ny][nx] == 'G') { cout << hands + 1 << endl; // show(knight); // show(bishop); return 0; } que.push(make_tuple(nx * 1000 + ny, hands + 1, board[ny][nx] == 'R' ? 'k' : 'b')); } } } } cout << -1 << endl; return 0; }