#include #include #include using namespace std; char in; int h,w,masu[504][504] = {}; struct joutai { int x; int y; int nb; int nanho; }; int check[504][504][2] = {}; queue Q; joutai saisho; int goalx,goaly; int ans = -1; int ndx[8] = {1,2,2,1,-1,-2,-2,-1}; int ndy[8] = {-2,-1,1,2,2,1,-1,-2}; int bdx[4] = {1,1,-1,-1}; int bdy[4] = {-1,1,1,-1}; void nyuryoku() { cin >> h >> w; for (int i = 2; i < h; i++) { for (int j = 2; j < w; j++) { cin >> in; if(in == 'S') { masu[i][j] = 1; saisho.x = i; saisho.y = j; saisho.nb = 1; saisho.nanho = 0; } else if(in == 'G') { masu[i][j] = 2; goalx = i; goaly = j; } else if(in == 'R') { masu[i][j] = 3; } else { masu[i][j] = 4; } } } } void keisan() { Q.push(saisho); while(1) { if(Q.size() == 0) { break; } joutai miru = Q.front(); Q.pop(); if(check[miru.x][miru.y][miru.nb] == 1) { continue; } check[miru.x][miru.y][miru.nb] = 1; joutai dainyu; if(miru.x == goalx && miru.y == goaly) { ans = miru.nanho; break; } if(miru.nb == 1) { for (int i = 0; i < 8; i++) { if(masu[miru.x + ndx[i]][miru.y + ndy[i]] == 4 || masu[miru.x + ndx[i]][miru.y + ndy[i]] == 3|| masu[miru.x + ndx[i]][miru.y + ndy[i]] == 2|| masu[miru.x + ndx[i]][miru.y + ndy[i]] == 1) { if(masu[miru.x + ndx[i]][miru.y + ndy[i]] == 3) { dainyu.nb = 2; } else { dainyu.nb = 1; } dainyu.x = miru.x + ndx[i]; dainyu.y = miru.y + ndy[i]; dainyu.nanho = miru.nanho + 1; Q.push(dainyu); } } } else if(miru.nb == 2) { for (int i = 0; i < 4; i++) { if(masu[miru.x + bdx[i]][miru.y + bdy[i]] == 4 || masu[miru.x + bdx[i]][miru.y + bdy[i]] == 3|| masu[miru.x + bdx[i]][miru.y + bdy[i]] == 2|| masu[miru.x + bdx[i]][miru.y + bdy[i]] == 1) { if(masu[miru.x + bdx[i]][miru.y + bdy[i]] == 3) { dainyu.nb = 1; } else { dainyu.nb = 2; } dainyu.x = miru.x + bdx[i]; dainyu.y = miru.y + bdy[i]; dainyu.nanho = miru.nanho + 1; Q.push(dainyu); } } } } } int main() { nyuryoku(); keisan(); cout << ans << endl; }