#include #include #include #include #include #include #include #include #include #include using namespace std; using ull = unsigned long long; bool used[2][500][500]; int ans = 1000000; int night_dx[8] = {2,1,1,2,-1,-1,-2,-2}; int night_dy[8] = {1,2,-2,-1,2,-2,-1,1}; int dx[4] = {-1,1,-1,1}; int dy[4] = {1,-1,-1,1}; int h,w; bool InBounds(pair test) { if(test.first >=0 && test.second >=0 && test.first < w && test.second < h) return true; else return false; } int main() { cin >> h >> w; vector board(h); queue> q; vector> cash; queue> counter; int dp[500][500]; for(auto&& x: dp) for(auto&& y : x) y = 100000; for(auto&& x : board) { cin >> x; } int start_x,start_y; for(int y = 0; y < h; ++y) { for(int x= 0; x < w; ++x) { if(board.at(y).at(x) == 'S') { start_x = x; start_y = y; break; } } } q.push(make_pair(start_x,start_y)); counter.push(make_pair(0,true)); while(!q.empty()) { pair test = q.front(); q.pop(); int num = counter.front().first; bool is_night = counter.front().second; counter.pop(); if(board.at(test.second).at(test.first) == 'G') { ans = min(ans,num); continue; } if(board.at(test.second).at(test.first) == 'R') { is_night ^= true; } if(is_night) { for(int i =0; i < 8; ++i) { pair tmp = make_pair(test.first + night_dx[i],test.second + night_dy[i]); if(InBounds(tmp) && !used[is_night][tmp.second][tmp.first]) { q.push(tmp); counter.push(make_pair(num+1,is_night)); used[is_night][tmp.second][tmp.first] = true; } } } else { for(int i =0; i < 4; ++i) { pair tmp = make_pair(test.first + dx[i],test.second + dy[i]); if(InBounds(tmp) && !used[is_night][tmp.second][tmp.first]) { q.push(tmp); counter.push(make_pair(num+1,is_night)); used[is_night][tmp.second][tmp.first] = true; } } } } if(ans != 1000000) cout << ans << endl; else cout << -1 << endl; }