結果

問題 No.3504 Insert Maze
コンテスト
ユーザー カプモカ
提出日時 2026-04-18 19:28:34
言語 PyPy3
(7.3.17)
コンパイル:
pypy3 -mpy_compile _filename_
実行:
pypy3 _filename_
結果
AC  
実行時間 940 ms / 2,000 ms
コード長 2,495 bytes
記録
記録タグの例:
初AC ショートコード 純ショートコード 純主流ショートコード 最速実行時間
コンパイル時間 295 ms
コンパイル使用メモリ 85,504 KB
実行使用メモリ 247,552 KB
最終ジャッジ日時 2026-04-18 19:28:59
合計ジャッジ時間 19,658 ms
ジャッジサーバーID
(参考情報)
judge3_0 / judge2_0
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 85
権限があれば一括ダウンロードができます

ソースコード

diff #
raw source code

import sys
from collections import deque

def solve():
    readline = sys.stdin.readline
    input_value = readline().split()
    H = int(input_value[0])
    W = int(input_value[1])

    grid = [None] * H
    for h in range(H):
        grid[h] = readline().rstrip().replace('S', '.').replace('G', '.')

    can_reach_goal = [[False] * W for _ in range(H)]
    row_has_reach = [[False] * W for _ in range(H)]
    col_has_reach = [[False] * W for _ in range(H)]

    if grid[H-1][W-1] == '.':
        can_reach_goal[H-1][W-1] = True
        row_has_reach[H-1][W-1] = True
        col_has_reach[H-1][W-1] = True

    for y in range(H-1, -1, -1):
        for x in range(W-1, -1, -1):
            if y == H-1 and x == W-1:
                continue
            
            if grid[y][x] == '.':
                if (y + 1 < H and can_reach_goal[y+1][x]) or (x + 1 < W and can_reach_goal[y][x+1]):
                    can_reach_goal[y][x] = True
            
            if can_reach_goal[y][x]:
                row_has_reach[y][x] = True
                col_has_reach[y][x] = True
            else:
                if x + 1 < W and row_has_reach[y][x+1]:
                    row_has_reach[y][x] = True
                if y + 1 < H and col_has_reach[y+1][x]:
                    col_has_reach[y][x] = True

    dist = [[-1] * W for _ in range(H)]
    queue = deque()
    dist[0][0] = 0
    queue.append((0,0))

    dy = [-1, 1, 0, 0]
    dx = [0, 0, -1, 1]
    Magic = H + W
    ans = -1
    check_point = False

    while queue:
        y, x = queue.popleft()
        
        if check_point and dist[y][x] >= Magic - 1:
            break
        if dist[y][x] >= Magic:
            break

        if y == H - 1 and x == W - 1:
            ans = dist[y][x]
            break
        
        if dist[y][x] == y + x:
            if y + 1 < H and row_has_reach[y + 1][x]:
                check_point = True
            if x + 1 < W and col_has_reach[y][x + 1]:
                check_point = True
        
        for i in range(4):
            ny = y + dy[i]
            nx = x + dx[i]

            if 0 <= ny < H and 0 <= nx < W:
                if grid[ny][nx] == '.' and dist[ny][nx] == -1:
                    dist[ny][nx] = dist[y][x] + 1
                    queue.append((ny, nx))

    if check_point:
        if ans == -1 or ans > Magic - 1:
            ans = Magic - 1
    else:
        if ans == -1 or ans > Magic:
            ans = Magic

    print(ans)

if __name__ == '__main__':
    solve()
0