#include #include #include using namespace std; char in[500][500]; int h,w,masu[500][500] = {}; struct joutai { int x; int y; int nb; int nanho; }; int check[500][500][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 = 0; i < h; i++) { scanf("%s",in[i]); for (int j = 0; j < w; j++) { if(in[i][j] == 'S') { masu[i][j] = 1; saisho.x = i; saisho.y = j; saisho.nb = 1; saisho.nanho = 0; } else if(in[i][j] == 'G') { masu[i][j] = 2; goalx = i; goaly = j; } else if(in[i][j] == '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 || (miru.x + ndx[i] < 500) || (miru.y + ndy[i] < 500)) { 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 || (miru.x + bdx[i] < 500) || (miru.y + bdy[i] < 500)) { 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; }