#include using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int h, w; cin >> h >> w; vector s(h); for (int i = 0; i < h; i++) cin >> s[i]; int hh = 2 * h - 1; int ww = 2 * w - 1; int W = ww + 2; int H = hh + 2; int SZ = W * H; int ss = -1, gg = -1; vector d(SZ, -1); auto norm = [&](int idx) { if (idx < 0) idx += SZ; // Python の負の添字を再現 return idx; }; for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) { int idx = 2 * i * W + 2 * j; if (s[i][j] == 'S') ss = idx; else if (s[i][j] == 'G') gg = idx; else if (s[i][j] == '#') d[idx] = -2; } } for (int i = hh; i <= hh + 1; i++) { for (int j = 0; j < W; j++) { d[i * W + j] = -2; } } for (int i = 0; i < H; i++) { for (int j = ww; j <= ww + 1; j++) { d[i * W + j] = -2; } } deque q; q.push_back(ss); d[ss] = 0; vector dij = {1, -1, W, -W}; vector dij2; for (int x : dij) dij2.push_back(2 * x); vector di2 = {2 * W, -2 * W}; vector dj2 = {2, -2}; while (!q.empty()) { int i = q.front(); q.pop_front(); int ii = i / W; int jj = i % W; for (int D : dij) { int j = norm(i + D); if (d[j] == -1) { d[j] = d[i] + 1; q.push_back(j); } } if (ii % 2 == 0 && jj % 2 == 0) { for (int D : dij2) { int j = norm(i + D); if (d[j] == -1) { d[j] = d[i] + 1; q.push_back(j); } } } if (ii % 2 == 0 && jj % 2 == 1) { for (int D : di2) { int j = norm(i + D); if (d[j] == -1) { d[j] = d[i] + 1; q.push_back(j); } } } if (ii % 2 == 1 && jj % 2 == 0) { for (int D : dj2) { int j = norm(i + D); if (d[j] == -1) { d[j] = d[i] + 1; q.push_back(j); } } } if (d[gg] != -1) { cout << d[gg] << '\n'; return 0; } } return 0; }