#include int h, w; char str[500][501]; int dp[2][500][500]; #define MAX 500 * 500 * 2 int queue_i[MAX]; int queue_j[MAX]; int queue_v[MAX]; // step (+1) int queue_s[MAX]; // knight : 0, bishop : 1 int set, get; int next_i[2][8] = { { -2, -2, -1, -1, +1, +1, +2, +2 }, { -1, -1, +1, +1 } }; int next_j[2][8] = { { -1, +1, -2, +2, -2, +2, -1, +1 }, { -1, +1, -1, +1 } }; int next_n[2] = { 8, 4 }; int in(int i, int j) { return 0 <= i && i < h && 0 <= j && j < w; } int main() { scanf("%d%d", &h, &w); for(int i = 0; i < h; i++) { scanf("%s", str[i]); } int s_i, s_j, g_i, g_j; for(int i = 0; i < h; i++) { for(int j = 0; j < w; j++) { if(str[i][j] == 'S') { s_i = i; s_j = j; } if(str[i][j] == 'G') { g_i = i; g_j = j; } } } dp[2][s_i][s_j] = 1; queue_i[set] = s_i; queue_j[set] = s_j; queue_v[set] = 1; queue_s[set] = 0; set++; while(get != set) { int i, j, v, s; i = queue_i[get]; j = queue_j[get]; v = queue_v[get]; s = queue_s[get]; if(str[i][j] == 'R') { s = (! s); } for(int k = 0; k < next_n[s]; k++) { int ii = i + next_i[s][k]; int jj = j + next_j[s][k]; if( in(ii, jj) && dp[s][ii][jj] == 0 ) { dp[s][ii][jj] = v + 1; queue_i[set] = ii; queue_j[set] = jj; queue_v[set] = v + 1; queue_s[set] = s; set++; } } get++; } int ans; int k = dp[0][g_i][g_j]; int b = dp[1][g_i][g_j]; if( k == 0 || b == 0 ) { ans = k < b ? b : k; } else { ans = k < b ? k : b; } printf("%d\n", ans - 1); return 0; }