#include using namespace std; #define rep(i,a,b) for(int i=a;i tiii; typedef pair pti; int dx[2][8] = { { -2, -1, 1, 2, -2, -1, 1, 2 } ,{ -1, 1, -1, 1, 0, 0, 0, 0 } }; int dy[2][8] = { { -1, -2, -2, -1, 1, 2, 2, 1 } ,{ -1, -1, 1,1, 0, 0, 0, 0 } }; int dnum[2] = { 8, 4 }; int main() { int H, W; cin >> H >> W; vector s(H); rep(i, 0, H) cin >> s[i]; int sx, sy; rep(y, 0, H) rep(x, 0, W) if (s[y][x] == 'S') { sx = x; sy = y; } set done; queue que; que.push(pti(tiii(sx, sy, 0), 0)); while (!que.empty()) { pti p = que.front(); que.pop(); if (done.find(p.first) != done.end()) continue; done.insert(p.first); int x = get<0>(p.first); int y = get<1>(p.first); int type = get<2>(p.first); int cost = p.second; //printf("(%d,%d,%d,%d)\n", x, y, type, cost); if (s[y][x] == 'G') { cout << cost << endl; return 0; } rep(i, 0, dnum[type]) { int xx = x + dx[type][i]; int yy = y + dy[type][i]; if (xx < 0 || W <= xx) continue; if (yy < 0 || H <= yy) continue; int ttype; if (s[yy][xx] == 'R') ttype = (type + 1) % 2; else ttype = type; que.push(pti(tiii(xx, yy, ttype),cost + 1)); } } cout << -1 << endl; }