結果
| 問題 |
No.157 2つの空洞
|
| コンテスト | |
| ユーザー |
|
| 提出日時 | 2015-06-02 20:16:52 |
| 言語 | Python3 (3.13.1 + numpy 2.2.1 + scipy 1.14.1) |
| 結果 |
RE
|
| 実行時間 | - |
| コード長 | 2,107 bytes |
| コンパイル時間 | 93 ms |
| コンパイル使用メモリ | 12,928 KB |
| 実行使用メモリ | 11,264 KB |
| 最終ジャッジ日時 | 2024-07-06 13:44:55 |
| 合計ジャッジ時間 | 1,579 ms |
|
ジャッジサーバーID (参考情報) |
judge2 / judge1 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 4 |
| other | AC * 8 RE * 8 |
ソースコード
class DisjointSet(object):
def __init__(self, n):
self.parent = list(range(n))
self.rank = [0] * n
self.num = n # number of disjoint sets
def union(self, x, y):
self._link(self.find_set(x), self.find_set(y))
def _link(self, x, y):
if x == y:
return
self.num -= 1
if self.rank[x] > self.rank[y]:
self.parent[y] = x
else:
self.parent[x] = y
if self.rank[x] == self.rank[y]:
self.rank[y] += 1
def find_set(self, x):
xp = self.parent[x]
if xp != x:
self.parent[x] = self.find_set(xp)
return self.parent[x]
def read_data():
W, H = map(int, input().split())
maze = [input().strip() for h in range(H)]
return W, H, maze
import collections
def solve(W, H, maze):
maze = [[c == '.' for c in row] for row in maze]
djs = DisjointSet(W * H)
for h in range(1, H-1):
for w in range(1, W-1):
pos = h * W + w
if maze[h][w]:
if maze[h-1][w]:
djs.union(pos, pos - W)
elif maze[h][w-1]:
djs.union(pos, pos - 1)
else:
djs.union(pos, 0)
areas = collections.defaultdict(list)
for h in range(1, H-1):
for w in range(1, W-1):
p = djs.find_set(h * W + w)
if p:
areas[p].append((h, w))
a1, a2 = areas
frontiers = areas[a1]
dist = 0
while frontiers:
new_frontiers = []
for (h, w) in frontiers:
for nh, nw in [(h+1, w), (h-1, w), (h, w+1), (h, w-1)]:
if nh < 0 or nh >= H or nw < 0 or nw >= W:
continue
if djs.find_set(nh * W + nw) == a2:
return dist
elif not maze[nh][nw]:
maze[nh][nw] = True
new_frontiers.append((nh, nw))
frontiers = new_frontiers
dist += 1
if __name__ == '__main__':
W, H, maze = read_data()
print(solve(W, H, maze))