#include using namespace std; #undef _P #define _P(...) (void)printf(__VA_ARGS__) #define FORR(x,arr) for(auto&& x:arr) #define FOR(i,a,b) for (int i = (a); i < (b); i++) #define RFOR(i,a,b) for (int i = (b)-1; i >= (a); i--) #define REP(i,n) for (int i = 0; i < (n); i++) #define RREP(i,n) for (int i = (n)-1; i >= 0; i--) #define ALL(x) (x).begin(), (x).end() #define BIT(n) (1LL<<(n)) #define SZ(x) ((int)(x).size()) typedef long long ll; // ------------------------------------- typedef tuple IIII; int H, W; string S[500]; int sx, sy, gx, gy; bool seen[500][500][2]; vector> DY; vector> DX; void Main() { DY.push_back({-2,-1,1,2,2,1,-1,-2}); DX.push_back({1,2,2,1,-1,-2,-2,-1}); DY.push_back({-1,1,1,-1}); DX.push_back({1,1,-1,-1}); cin >> H >> W; REP(i, H) { cin >> S[i]; REP(j, W) { if (S[i][j] == 'S') sy=i, sx=j; else if (S[i][j] == 'G') gy=i, gx=j; } } queue q; q.push(make_tuple(0, 0, sy, sx)); while(!q.empty()) { int n = get<0>(q.front()); int t = get<1>(q.front()); int y = get<2>(q.front()); int x = get<3>(q.front()); q.pop(); if (x == gx && y == gy) { _P("%d\n", n); return; } int l = SZ(DY[t]); REP(i, l) { int dy = DY[t][i]; int dx = DX[t][i]; int ny = y + dy; int nx = x + dx; if (ny < 0 || ny >= H) continue; if (nx < 0 || nx >= W) continue; int nt = S[ny][nx] == 'R' ? !t : t; if (seen[ny][nx][nt]) continue; q.push(make_tuple(n+1, nt, ny, nx)); seen[ny][nx][nt] = 1; } } puts("-1"); } int main() { cin.tie(0); ios::sync_with_stdio(false); Main(); return 0; }