#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #define INF 100000000 #define mod7 10000000007 #define YJ 1145141919 #define INF_INT_MAX 2147483647 #define INF_LL_MAX 9223372036854775807 #define INF_LL 9223372036854775 #define EPS 1e-10 #define Pi acos(-1) #define LL long long #define ULL unsigned long long #define LD long double using namespace std; #define MAX_H 505 #define MAX_W 505 int H, W; int memo[MAX_H][MAX_W][2]; char field[MAX_H][MAX_W]; int Sx, Sy; void input(){ cin >> H >> W; for(int i = 0; i < H ; i++){ for(int j = 0; j < W; j++){ cin >> field[i][j]; if(field[i][j] == 'S'){ Sx = j; Sy = i; } } } } struct sStatus{ int job; int x,y; sStatus(int job, int x, int y) : job(job), x(x), y(y){} }; bool isInField(int x, int y){ return 0 <= x && x < W && 0 <= y && y < H; } int dx0[] = {-2,-1,1,2,-2,-1,1,2}; int dy0[] = {-1,-2,-2,-1,1,2,2,1}; int dx1[] = {-1,1,-1,1}; int dy1[] = {-1,-1,1,1}; int solve(){ fill((int*)memo, (int*)memo + MAX_H*MAX_W*2, INF); queue que; que.push(sStatus(0, Sx, Sy)); memo[Sy][Sx][0] = 0; while(que.size()){ sStatus st = que.front(); que.pop(); if(field[st.y][st.x] == 'G') return memo[st.y][st.x][st.job]; for(int d = 0; d < (st.job == 0 ? 8 : 4); d++){ int nx, ny; if(st.job == 0){ nx = st.x + dx0[d]; ny = st.y + dy0[d]; } else{ nx = st.x + dx1[d]; ny = st.y + dy1[d]; } if(isInField(nx,ny)){ int nextJob = st.job; if(field[ny][nx] == 'R'){ nextJob = (nextJob+1)%2; } if(memo[ny][nx][nextJob] == INF){ memo[ny][nx][nextJob] = memo[st.y][st.x][st.job] + 1; que.push(sStatus(nextJob, nx, ny)); } } } } return -1; } int main(){ input(); cout << solve() << endl; return 0; }