結果

問題 No.157 2つの空洞
ユーザー 🍡yurahuna🍡yurahuna
提出日時 2016-04-28 21:27:18
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 264 ms / 2,000 ms
コード長 1,308 bytes
コンパイル時間 173 ms
コンパイル使用メモリ 82,228 KB
実行使用メモリ 79,824 KB
最終ジャッジ日時 2024-04-15 05:12:12
合計ジャッジ時間 3,485 ms
ジャッジサーバーID
(参考情報)
judge2 / judge1
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 69 ms
67,672 KB
testcase_01 AC 65 ms
68,316 KB
testcase_02 AC 68 ms
69,092 KB
testcase_03 AC 96 ms
78,344 KB
testcase_04 AC 96 ms
78,480 KB
testcase_05 AC 121 ms
78,884 KB
testcase_06 AC 110 ms
78,788 KB
testcase_07 AC 94 ms
78,684 KB
testcase_08 AC 83 ms
74,824 KB
testcase_09 AC 123 ms
79,000 KB
testcase_10 AC 73 ms
71,080 KB
testcase_11 AC 113 ms
78,900 KB
testcase_12 AC 113 ms
78,720 KB
testcase_13 AC 109 ms
78,996 KB
testcase_14 AC 168 ms
79,444 KB
testcase_15 AC 264 ms
79,592 KB
testcase_16 AC 164 ms
79,160 KB
testcase_17 AC 210 ms
79,824 KB
testcase_18 AC 210 ms
79,496 KB
testcase_19 AC 93 ms
78,496 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

from queue import Queue

def inside(x, y):
    return 0 <= x < H and 0 <= y < W

dx = [1, 0, -1, 0]
dy = [0, 1, 0, -1]

def dfs(x, y, c):
    color[x][y] = c
    for k in range(4):
        nx = x + dx[k]; ny = y + dy[k]
        if inside(nx, ny) and s[nx][ny] == '.' and color[nx][ny] == -1:
            dfs(nx, ny, c)

INF = 99
def bfs(sx, sy, gx, gy):
    que = Queue()
    que.put((sx, sy))
    d = [[INF] * W for i in range(H)]
    d[sx][sy] = 0

    while que:
        x, y = que.get()
        if (x, y) == (gx, gy):
            break
        for k in range(4):
            nx = x + dx[k]; ny = y + dy[k]
            if inside(nx, ny) and d[nx][ny] == INF:
                d[nx][ny] = d[x][y] + (s[nx][ny] == '#')
                que.put((nx, ny))

    return d[gx][gy]


W, H = map(int, input().split())
s = []
for i in range(H):
    s.append(list(input()))

color = [[-1] * W for i in range(H)]
nxtcolor = 0
for i in range(H):
    for j in range(W):
        if s[i][j] == '.' and color[i][j] == -1:
            dfs(i, j, nxtcolor)
            nxtcolor += 1

ans = INF
for i1 in range(H):
    for j1 in range(W):
        for i2 in range(H):
            for j2 in range(W):
                if color[i1][j1] == 0 and color[i2][j2] == 1:
                    ans = min(ans, bfs(i1, j1, i2, j2))
print(ans)
0