#include using namespace std; using ll = long long; const ll INF = 1ll << 60; #define REP(i, n) for(ll i =0; i < ll(n); i++) template using V = vector; template bool chmax(A& a, B b) { return a bool chmin(A& a, B b) { return b> h >> w; V c(h); REP(i, h) cin >> c[i]; auto dist_from = [&](int sx, int sy) { V dist(h, V(w, INF)); queue> que; dist[sx][sy] = 0; que.emplace(sx, sy); constexpr int DX[4] = {1, 0, -1, 0}; constexpr int DY[4] = {0, 1, 0, -1}; while(!que.empty()) { auto [x, y] = que.front(); que.pop(); REP(i, 4) { int nx = x+DX[i], ny = y+DY[i]; if(nx < 0 || nx >= h || ny < 0 || ny >= w) continue; if(c[nx][ny] == '#') continue; if(chmin(dist[nx][ny], dist[x][y]+1)) { que.emplace(nx, ny); } } } return dist; }; int sx = -1, sy = -1, gx = -1, gy = -1; REP(i, h) REP(j, w) { if(c[i][j] == 'S') { sx = i, sy = j; } else if(c[i][j] == 'G') { gx = i, gy = j; } } auto ds = dist_from(sx, sy); auto dg = dist_from(gx, gy); ll ans = ds[gx][gy]; chmin(ans, h+w); REP(i, h-1) { ll tmp0 = INF, tmp1 = INF, tmp2 = INF, tmp3 = INF; REP(j, w) { chmin(tmp0, ds[i][j]-j); chmin(ans, dg[i+1][j]+j + tmp0 + 2); chmin(tmp1, dg[i][j]-j); chmin(ans, ds[i+1][j]+j + tmp1 + 2); chmin(tmp2, ds[i+1][j]-j); chmin(ans, dg[i][j]+j + tmp2 + 2); chmin(tmp3, dg[i+1][j]-j); chmin(ans, ds[i][j]+j + tmp3 + 2); } } REP(j, w-1) { ll tmp0 = INF, tmp1 = INF, tmp2 = INF, tmp3 = INF; REP(i, h) { chmin(tmp0, ds[i][j]-i); chmin(ans, dg[i][j+1]+i + tmp0 + 2); chmin(tmp1, dg[i][j]-i); chmin(ans, ds[i][j+1]+i + tmp1 + 2); chmin(tmp2, ds[i][j+1]-i); chmin(ans, dg[i][j]+i + tmp2 + 2); chmin(tmp3, dg[i][j+1]-i); chmin(ans, ds[i][j]+i + tmp3 + 2); } } cout << ans << '\n'; } int main() { cin.tie(0)->sync_with_stdio(0); testcase(); }