# pragma GCC target("avx2") # pragma GCC optimize("O3") # pragma GCC optimize("unroll-loops") #include #include #include #include using namespace std; #define overload4(_1,_2,_3,_4,name,...) name #define rep1(i,n) for (int i = 0; i < (n); ++i) #define rep2(i,m,n) for (int i = (m); i < (n); ++i) #define rep3(i,m,n,k) for (int i = (m); i < (n); i += (k)) #define rep(...) overload4(__VA_ARGS__, rep3, rep2, rep1)(__VA_ARGS__) vector> dij = {{0,1}, {1,0}, {0,-1}, {-1,0}}; int main() { int h,w; cin>>h>>w; string s[h]; rep (i,h){ cin>>s[i]; } int hh,ww; hh=2*h-1; ww=2*w-1; array ss,gg; rep(i,h){ rep(j,w){ if (s[i][j]=='S'){ ss[0]=2*i; ss[1]=2*j; s[i][j]='.'; } else if (s[i][j]=='G'){ gg[0]=2*i; gg[1]=2*j; s[i][j]='.'; } } } int d[hh][ww]; rep (i,hh){ rep (j,ww){ d[i][j]=-1; } } d[ss[0]][ss[1]]=0; queue> task; task.push(ss); while (task.size()>0){ array place=task.front(); task.pop(); int ii=place[0]; int jj=place[1]; vector> rin={}; for (auto [di,dj]:dij){ if (0<=ii+di and ii+di new_place={ii+di,jj+dj}; rin.emplace_back(new_place); } } if (ii%2==0 and jj%2==0){ for (auto [di,dj]:dij){ di*=2; dj*=2; //cout<<(ii+di)/2<<" "< new_place={ii+di,jj+dj}; rin.emplace_back(new_place); } } } if (ii%2==0 and jj%2==1){ for (int di:{2,-2}){ if (0<=ii+di and ii+di new_place={ii+di,jj}; rin.emplace_back(new_place); } } } if (ii%2==1 and jj%2==0){ for (int dj:{2,-2}){ if (0<=jj+dj and jj+dj new_place={ii,jj+dj}; rin.emplace_back(new_place); } } } for (auto i:rin){ //cout<