結果

問題 No.157 2つの空洞
ユーザー norioc
提出日時 2024-08-21 02:30:44
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 60 ms / 2,000 ms
コード長 1,194 bytes
コンパイル時間 598 ms
コンパイル使用メモリ 82,136 KB
実行使用メモリ 65,572 KB
最終ジャッジ日時 2024-08-21 02:30:48
合計ジャッジ時間 2,857 ms
ジャッジサーバーID
(参考情報)
judge2 / judge5
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 4
other AC * 16
権限があれば一括ダウンロードができます

ソースコード

diff #

from collections import deque
from collections.abc import Iterator


def neighbors4(r: int, c: int) -> Iterator[tuple[int, int]]:
    for dr, dc in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
        nr = r + dr
        nc = c + dc
        if not (0 <= nr < H and 0 <= nc < W): continue
        yield nr, nc


def fill(row, col, g, val):
    q = deque([(row, col)])
    while q:
        r, c = q.popleft()
        if g[r][c] == val: continue
        g[r][c] = val

        for nr, nc in neighbors4(r, c):
            if g[nr][nc] == val: continue
            if G[nr][nc] == '#': continue
            q.append((nr, nc))


INF = 1 << 60
W, H = map(int, input().split())
G = [input() for _ in range(H)]

g = [[-1] * W for _ in range(H)]
marker = 0
for i in range(H):
    for j in range(W):
        if g[i][j] != -1: continue
        if G[i][j] == '#': continue
        fill(i, j, g, marker)
        marker += 1

ans = INF
for r1 in range(H):
    for c1 in range(W):
        if g[r1][c1] != 0: continue
        for r2 in range(H):
            for c2 in range(W):
                if g[r2][c2] != 1: continue
                d = abs(r1 - r2) + abs(c1 - c2)
                ans = min(ans, d - 1)

print(ans)
0