#include #include #include #include #include #include #include typedef long long ll; #define fi first #define se second const ll mod = 1000000007; // 123456789 using namespace std; /////////////////////////////////////////////// // // /////////////////////////////////////////////// //////////////////////////////////////////////// //////////////////////////////////////////////// int H; int W; string S[512]; int nx[8] = { -2, -1, 1, 2, 2, 1, -1, -2 }; int ny[8] = { 1, 2, 2, 1, -1, -2, -2, -1 }; int bx[4] = { 1, 1, -1, -1 }; int by[4] = { 1, -1, 1, -1 }; int ndist[512][512]; int bdist[512][512]; int ch[512][512]; int flag[512][512]; pairQ[512345]; bool q[512345];//ナイトのときは0 int sx, sy; int gx, gy; int main(){ cin>>H>>W; int i; int j; int x; int y; int Pop = 0; int Push = 0; fill( bdist[0], bdist[512], 1123456789 ); fill( ndist[0], ndist[512], 1123456789 ); fill( ch[0], ch[512], 0 );//変わるところは1 fill( flag[0], flag[512], 3 );//ナイトで通ったら-2、 for( i = 0; i < H; i++ ){ cin>>S[i]; } for( i = 0; i < H; i++ ){ for( j = 0; j < W; j++ ){ if( S[i][j] == 'S' ){ sx = j; sy = i; ndist[j][i] = 0; Q[Push].fi = j; Q[Push].se = i; q[Push] = 0; Push++; } if( S[i][j] == 'G' ){ gx = j; gy = i; } if( S[i][j] == 'R' ){ ch[j][i] = 1; } } } while( Pop != Push ){ if( Q[Pop].fi == gx && Q[Pop].se == gy ) break; if( q[Pop] ){//現在ビショップのとき if( flag[Q[Pop].fi][Q[Pop].se]%2 ){ for( i = 0; i < 4; i++ ){ x = Q[Pop].fi + bx[i]; y = Q[Pop].se + by[i]; if( 0 <= x && x < W && 0 <= y && y < H ){//移動先が範囲内かどうか if( ch[x][y] == 0 && (flag[x][y]%2) == 1 ){//移動後ビショップ bdist[x][y] = min( bdist[x][y], bdist[Q[Pop].fi][Q[Pop].se]+1); Q[Push].fi = x; Q[Push].se = y; q[Push] = 1; Push++; } else if( ch[x][y] && flag[x][y] > 1 ){//移動後ナイト ndist[x][y] = min( ndist[x][y], bdist[Q[Pop].fi][Q[Pop].se]+1); Q[Push].fi = x; Q[Push].se = y; q[Push] = 0; Push++; } } } flag[Q[Pop].fi][Q[Pop].se]--; } } else{//現在ナイトのとき if( flag[Q[Pop].fi][Q[Pop].se] > 1 ){ for( i = 0; i < 8; i++ ){ x = Q[Pop].fi + nx[i]; y = Q[Pop].se + ny[i]; if( 0 <= x && x < W && 0 <= y && y < H ){//移動先が範囲内かどうか if( ch[x][y] && (flag[x][y]%2) == 1 ){//移動後ビショップ bdist[x][y] = min( bdist[x][y], ndist[Q[Pop].fi][Q[Pop].se]+1); Q[Push].fi = x; Q[Push].se = y; q[Push] = 1; Push++; } else if( ch[x][y] == 0 && flag[x][y] > 1 ){//移動後ナイト ndist[x][y] = min( ndist[x][y], ndist[Q[Pop].fi][Q[Pop].se]+1); Q[Push].fi = x; Q[Push].se = y; q[Push] = 0; Push++; } } } flag[Q[Pop].fi][Q[Pop].se] -= 2; } } Pop++; Pop%=500000; Push%=500000; } int ans; ans = min( ndist[gx][gy], bdist[gx][gy] ); /* puts("ナイトで着地"); for( i = 0; i < H; i++ ){ for( j = 0; j < W; j++ ){ if( j ) printf(" "); printf("%d", ndist[i][j] ); } puts(""); } puts("ビショップで着地"); for( i = 0; i < H; i++ ){ for( j = 0; j < W; j++ ){ if( j ) printf(" "); printf("%d", bdist[i][j] ); } puts(""); } puts("flag"); for( i = 0; i < H; i++ ){ for( j = 0; j < W; j++ ){ if( j ) printf(" "); printf("%d", flag[i][j] ); } puts(""); } for( i = 0; i < Pop; i++ ){ printf("(%d, %d)\n", Q[i].fi, Q[i].se ); } cout<