#include #include #include #include #include #include #include #include #include using namespace std; #define ll long long int #define ti4 tuple #define pii pair int B[2][500][500]; int red[500][500]; int main() { int H, W; cin >> H >> W; fill(&red[0][0], &red[0][0] + 500 * 500, 0); fill(&B[0][0][0], &B[0][0][0] + 2 * 500 * 500, 1e6); pii start; pii end; for(int i = 0;i < H;i++) { string s; cin >> s; for(int j = 0;j < W;j++) { if(s[j] == 'S') { start = make_pair(j, i); } else if(s[j] == 'G') { end = make_pair(j, i); } else if(s[j] == 'R') { red[i][j] = 1; } } } priority_queue, greater> q; q.push(make_tuple(0, start.first, start.second, 0)); B[0][start.second][start.first] = 0; while(!q.empty()) { int count, x, y, board; tie(count, x, y, board) = q.top(); //cout << count << "," << x << "," << y << "," << board << endl; q.pop(); if(x == end.first && y == end.second) { cout << count << endl; return 0; } int nc = count + 1; if(board == 0) { pii shift[] = {make_pair(-1,-2),make_pair(-2,-1),make_pair(1,-2),make_pair(2,-1), make_pair(-1,2),make_pair(-2,1),make_pair(1,2),make_pair(2,1)}; for(int i = 0;i < 8;i++) { int nx = x + shift[i].first; int ny = y + shift[i].second; if(nx >= 0 && nx < W && ny >= 0 && ny < H) { if(B[board][ny][nx] <= nc) { continue; } B[board][ny][nx] = nc; if(red[ny][nx]) { q.push(make_tuple(nc, nx, ny, 1)); } else { q.push(make_tuple(nc, nx, ny, 0)); } } } } else { pii shift[] = {make_pair(-1,-1),make_pair(1,-1),make_pair(-1,1),make_pair(1,1)}; for(int i = 0;i < 4;i++) { int nx = x + shift[i].first; int ny = y + shift[i].second; if(nx >= 0 && nx < W && ny >= 0 && ny < H) { if(B[board][ny][nx] <= nc) { continue; } B[board][ny][nx] = nc; if(red[ny][nx]) { q.push(make_tuple(nc, nx, ny, 0)); } else { q.push(make_tuple(nc, nx, ny, 1)); } } } } } cout << -1 << endl; return 0; }