#define _CRT_SECURE_NO_WARNINGS #define _USE_MATH_DEFINES #include using namespace std; using i8 = int8_t; using u8 = uint8_t; using i16 = int16_t; using u16 = uint16_t; using i32 = int32_t; using u32 = uint32_t; using i64 = int64_t; using u64 = uint64_t; using f32 = float_t; using f64 = double_t; using usize = size_t;using str = string; template using vec = vector; #define times(n, i) for (i32 i = 0; i < (n); i++) #define range(n, m, i) for (i32 i = (n); i < (m); i++) #define upto(n, m, i) for (i32 i = (n); i <= (m); i++) #define downto(n, m, i) for (i32 i = (n); i >= (m); i--) #define foreach(xs, x) for (auto &x : (xs)) #define all(xs) (xs).begin(), (xs).end() #define sortall(xs) sort(all(xs)) #define reverseall(xs) reverse(all(xs)) #define uniqueall(xs) (xs).erase(unique(all(xs)), (xs).end()) #define maximum(xs) *max_element(all(xs)) #define minimum(xs) *min_element(all(xs)) const i64 MOD = 1000000007; vec m; vec> fp[2]; i32 sx, sy, gx, gy; i32 knight_x[8] = { -2, -1, 1, 2, 2, 1, -1, -2 }; i32 knight_y[8] = { -1, -2, -2, -1, 1, 2, 2, 1 }; i32 bishop_x[4] = { -1, 1, 1, -1 }; i32 bishop_y[4] = { -1, -1, 1, 1 }; i32 main() { i32 h, w; cin >> h >> w; m.resize(h); fp[0].resize(h); fp[1].resize(h); times(h, i) { cin >> m[i]; fp[0][i].resize(w); fp[1][i].resize(w); times(w, j) { if (m[i][j] == 'S') { sx = j; sy = i; } else if (m[i][j] == 'G') { gx = j; gy = i; } fp[0][i][j] = -1; fp[1][i][j] = -1; } } i32 last_t = 0; set> rest; rest.insert(make_tuple(0, sx, sy, 0)); while (rest.size()) { i32 turn = get<0>(*rest.begin()); i32 x = get<1>(*rest.begin()); i32 y = get<2>(*rest.begin()); i32 t = get<3>(*rest.begin()); rest.erase(rest.begin()); if (fp[t][y][x] > -1) continue; fp[t][y][x] = turn; if (x == gx && y == gy) { last_t = t; break; } if (m[y][x] == 'R') t ^= 1; if (t == 0) { times(8, i) { i32 nx = x + knight_x[i]; i32 ny = y + knight_y[i]; if (0 <= nx && nx < w && 0 <= ny && ny < h) { rest.insert(make_tuple(turn+1, nx, ny, t)); } } } else { times(4, i) { i32 nx = x + bishop_x[i]; i32 ny = y + bishop_y[i]; if (0 <= nx && nx < w && 0 <= ny && ny < h) { rest.insert(make_tuple(turn+1, nx, ny, t)); } } } } cout << fp[last_t][gy][gx] << endl; return 0; }