#include using namespace std; typedef long long ll; typedef vector< int > vi; typedef vector< vi > vvi; typedef vector< vvi > vvvi; typedef vector< ll > vl; typedef vector< vl > vvl; typedef pair< int, int > pii; typedef vector< pii > vp; typedef vector< double > vd; typedef vector< vd > vvd; typedef vector< string > vs; template< class T1, class T2 > int upmin( T1 &x, T2 v ){ if( x > v ){ x = v; return 1; } return 0; } template< class T1, class T2 > int upmax( T1 &x, T2 v ){ if( x < v ){ x = v; return 1; } return 0; } const int INF = 0x3f3f3f3f; const int kdx[] = { 1, 1, -1, -1, 2, 2, -2, -2 }; const int kdy[] = { 2, -2, 2, -2, 1, -1, 1, -1 }; const int bdx[] = { 1, 1, -1, -1 }; const int bdy[] = { -1, 1, -1, 1 }; int H, W; vs G; void init(){ cin >> H >> W; G = vs( H ); for( int i = 0; i < H; ++i ) cin >> G[ i ]; } int sx, sy; void preprocess(){ for( int i = 0; i < H; ++i ) for( int j = 0; j < W; ++j ) if( G[ i ][ j ] == 'S' ) sx = i, sy = j; } int in_range( int x, int y ){ return 0 <= x and x < H and 0 <= y and y < W; } void solve(){ vvvi dis = vvvi( H, vvi( W, vi( 2, INF ) ) ); queue< tuple< int, int, int, int > > que; que.emplace( dis[ sx ][ sy ][ 0 ] = 0, sx, sy, 0 ); while( not que.empty() ){ int d, x, y, t; tie( d, x, y, t ) = que.front(); que.pop(); if( dis[ x ][ y ][ t ] != d ) continue; if( G[ x ][ y ] == 'G' ) cout << d << endl, exit( 0 ); if( t == 0 ){ for( int di = 0; di < 8; ++di ){ int nx = x + kdx[ di ]; int ny = y + kdy[ di ]; if( not in_range( nx, ny ) ) continue; int nt = t; nt ^= G[ nx ][ ny ] == 'R'; if( upmin( dis[ nx ][ ny ][ nt ], dis[ x ][ y ][ t ] + 1 ) ) que.emplace( dis[ nx ][ ny ][ nt ], nx, ny, nt ); } } else{ for( int di = 0; di < 4; ++di ){ int nx = x + bdx[ di ]; int ny = y + bdy[ di ]; if( not in_range( nx, ny ) ) continue; int nt = t; nt ^= G[ nx ][ ny ] == 'R'; if( upmin( dis[ nx ][ ny ][ nt ], dis[ x ][ y ][ t ] + 1 ) ) que.emplace( dis[ nx ][ ny ][ nt ], nx, ny, nt ); } } } cout << -1 << endl; } signed main(){ ios::sync_with_stdio( 0 ); init(); preprocess(); solve(); return 0; }