結果

問題 No.157 2つの空洞
ユーザー lam6er
提出日時 2025-03-20 18:45:35
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 63 ms / 2,000 ms
コード長 2,104 bytes
コンパイル時間 167 ms
コンパイル使用メモリ 82,256 KB
実行使用メモリ 67,044 KB
最終ジャッジ日時 2025-03-20 18:45:48
合計ジャッジ時間 1,877 ms
ジャッジサーバーID
(参考情報)
judge3 / judge5
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 4
other AC * 16
権限があれば一括ダウンロードができます

ソースコード

diff #

import sys
import heapq
from collections import deque

def main():
    input = sys.stdin.read().split()
    idx = 0
    W = int(input[idx])
    idx += 1
    H = int(input[idx])
    idx += 1
    grid = []
    for _ in range(H):
        line = input[idx]
        grid.append(list(line))
        idx += 1

    visited = [[False for _ in range(W)] for _ in range(H)]
    regions = []

    for y in range(H):
        for x in range(W):
            if grid[y][x] == '.' and not visited[y][x]:
                queue = deque()
                queue.append((x, y))
                visited[y][x] = True
                current_region = []
                while queue:
                    cx, cy = queue.popleft()
                    current_region.append((cx, cy))
                    for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
                        nx = cx + dx
                        ny = cy + dy
                        if 0 <= nx < W and 0 <= ny < H and not visited[ny][nx] and grid[ny][nx] == '.':
                            visited[ny][nx] = True
                            queue.append((nx, ny))
                regions.append(current_region)

    region_A = regions[0]
    region_B = regions[1]
    region_b_set = set((x, y) for (x, y) in region_B)

    INF = float('inf')
    distance = [[INF for _ in range(W)] for _ in range(H)]
    heap = []
    for (x, y) in region_A:
        distance[y][x] = 0
        heapq.heappush(heap, (0, x, y))

    dirs = [(-1, 0), (1, 0), (0, -1), (0, 1)]

    while heap:
        current_cost, x, y = heapq.heappop(heap)
        if (x, y) in region_b_set:
            print(current_cost)
            return
        if current_cost > distance[y][x]:
            continue
        for dx, dy in dirs:
            nx = x + dx
            ny = y + dy
            if 0 <= nx < W and 0 <= ny < H:
                new_cost = current_cost + (1 if grid[ny][nx] == '#' else 0)
                if new_cost < distance[ny][nx]:
                    distance[ny][nx] = new_cost
                    heapq.heappush(heap, (new_cost, nx, ny))

if __name__ == "__main__":
    main()
0