#include #include typedef long long ll; typedef long double lb; using namespace std; using namespace atcoder; #define all(x) (x).begin(), (x).end() #define OVERLOAD_REP(_1, _2, _3, name, ...) name #define REP1(i, n) for (auto i = std::decay_t{}; (i) != (n); ++(i)) #define REP2(i, l, r) for (auto i = (l); (i) != (r); ++(i)) #define rep(...) OVERLOAD_REP(__VA_ARGS__, REP2, REP1)(__VA_ARGS__) template bool chmin(T& a, const T& b){if(a > b){a = b; return 1;} return 0;} template bool chmax(T& a, const T& b){if(a < b){a = b; return 1;} return 0;} const ll INF = 1000000000000000000; // 10^18 int main(){ ll h,w; cin >> h >> w; vector> c(h,vector(w)); rep(i,h){ rep(j,w){ cin >> c[i][j]; } } //h = iにSがあるか vector S_h(h,false); vector S_w(w,false); vector G_h(h,false); vector G_w(w,false); S_h[0] = true; S_w[0] = true; G_h[h-1] = true; G_w[w-1] = true; //Sを埋める rep(i,h){ rep(j,w){ if(c[i][j] == 'G'){ if(i != 0 && c[i-1][j] == 'S'){ c[i][j] = 'S'; S_h[i] = true; S_w[j] = true; cout << h+w-2 << endl; return 0; } if(j != 0 && c[i][j-1] == 'S'){ c[i][j] = 'S'; S_h[i] = true; S_w[j] = true; cout << h+w-2 << endl; return 0; } } if(c[i][j] == '.'){ if(i != 0 && c[i-1][j] == 'S'){ c[i][j] = 'S'; S_h[i] = true; S_w[j] = true; } if(j != 0 && c[i][j-1] == 'S'){ c[i][j] = 'S'; S_h[i] = true; S_w[j] = true; } } } } //Gを埋める for(ll i = h-1; i >= 0;i--){ for(ll j = w-1;j >= 0;j--){ if(c[i][j] == '.'){ if(i != h-1 && c[i+1][j] == 'G'){ c[i][j] = 'G'; G_h[i] = true; G_w[j] = true; } if(j != w-1 && c[i][j+1] == 'G'){ c[i][j] = 'G'; G_h[i] = true; G_w[j] = true; } } } } //一つ挿入で行けるか //hについて、(0-indexの)iとi+1の間に挿入できるか for(int i = 0;i < h-1;i++){ if(S_h[i] && G_h[i+1]){ cout << h+w-1 << endl; return 0; } } for(int j = 0;j < w-1;j++){ if(S_w[j] && G_w[j+1]){ cout << h+w-1 << endl; return 0; } } cout << h + w << endl; return 0; }