#include #include #include #include using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); int H, W; cin >> H >> W; vector g(H); for (int i = 0; i < H; i++) cin >> g[i]; auto passable = [&](int i, int j) -> bool { return g[i][j] == '.' || g[i][j] == 'S' || g[i][j] == 'G'; }; // fwd[i][j] : (0,0) から右・下移動のみで (i,j) に到達可能か vector> fwd(H, vector(W, false)); fwd[0][0] = true; for (int i = 0; i < H; i++) { for (int j = 0; j < W; j++) { if (!fwd[i][j]) continue; if (j + 1 < W && passable(i, j + 1)) fwd[i][j + 1] = true; if (i + 1 < H && passable(i + 1, j)) fwd[i + 1][j] = true; } } // rev[i][j] : (i,j) から右・下移動のみで G=(H-1,W-1) に到達可能か // (G から左・上への逆伝搬で求める) vector> rev(H, vector(W, false)); rev[H - 1][W - 1] = true; for (int i = H - 1; i >= 0; i--) { for (int j = W - 1; j >= 0; j--) { if (!rev[i][j]) continue; if (j - 1 >= 0 && passable(i, j - 1)) rev[i][j - 1] = true; if (i - 1 >= 0 && passable(i - 1, j)) rev[i - 1][j] = true; } } // ---- 超能力 0 回 ---- if (fwd[H - 1][W - 1]) { cout << H + W - 2 << '\n'; return 0; } // ---- 超能力 1 回 ---- // 列挿入: 列 c と c+1 の間に '.' 列を挿入 (c : 0-indexed, 0..W-2) // "列 c に到達できた最小行" min_r 以降の行で、元の列 c+1 が passable かつ rev = true なら OK { // 各列 c について min_row_fwd[c] = min{i : fwd[i][c]=1} (なければ H) vector min_row_fwd(W, H); for (int j = 0; j < W; j++) { for (int i = 0; i < H; i++) { if (fwd[i][j]) { min_row_fwd[j] = i; break; } } } for (int c = 0; c + 1 < W; c++) { if (min_row_fwd[c] == H) continue; // 列 c に未到達 // 列 c+1 の suffix: suf[i] = (i 以降に passable && rev の行が存在するか) bool suf = false; for (int i = H - 1; i >= min_row_fwd[c]; i--) { if (passable(i, c + 1) && rev[i][c + 1]) { suf = true; break; } } if (suf) { cout << H + W - 1 << '\n'; return 0; } } } // 行挿入: 行 r と r+1 の間に '.' 行を挿入 (r : 0-indexed, 0..H-2) // "行 r に到達できた最小列" min_c 以降の列で、元の行 r+1 が passable かつ rev = true なら OK { vector min_col_fwd(H, W); for (int i = 0; i < H; i++) { for (int j = 0; j < W; j++) { if (fwd[i][j]) { min_col_fwd[i] = j; break; } } } for (int r = 0; r + 1 < H; r++) { if (min_col_fwd[r] == W) continue; // 行 r に未到達 bool suf = false; for (int j = W - 1; j >= min_col_fwd[r]; j--) { if (passable(r + 1, j) && rev[r + 1][j]) { suf = true; break; } } if (suf) { cout << H + W - 1 << '\n'; return 0; } } } // ---- 超能力 2 回 (常に到達可能) ---- cout << H + W << '\n'; return 0; }