結果
| 問題 |
No.157 2つの空洞
|
| コンテスト | |
| ユーザー |
brthyyjp
|
| 提出日時 | 2022-03-21 14:04:52 |
| 言語 | PyPy3 (7.3.15) |
| 結果 |
AC
|
| 実行時間 | 60 ms / 2,000 ms |
| コード長 | 2,059 bytes |
| コンパイル時間 | 346 ms |
| コンパイル使用メモリ | 81,664 KB |
| 実行使用メモリ | 66,176 KB |
| 最終ジャッジ日時 | 2024-10-08 20:41:31 |
| 合計ジャッジ時間 | 2,155 ms |
|
ジャッジサーバーID (参考情報) |
judge4 / judge1 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 4 |
| other | AC * 16 |
ソースコード
class UnionFind:
def __init__(self, n):
self.par = [-1]*n
self.rank = [0]*n
def Find(self, x):
if self.par[x] < 0:
return x
else:
self.par[x] = self.Find(self.par[x])
return self.par[x]
def Unite(self, x, y):
x = self.Find(x)
y = self.Find(y)
if x != y:
if self.rank[x] < self.rank[y]:
self.par[y] += self.par[x]
self.par[x] = y
else:
self.par[x] += self.par[y]
self.par[y] = x
if self.rank[x] == self.rank[y]:
self.rank[x] += 1
def Same(self, x, y):
return self.Find(x) == self.Find(y)
def Size(self, x):
return -self.par[self.Find(x)]
from collections import deque
INF = 10**18
w, h = map(int, input().split())
C = [str(input()) for i in range(h)]
uf = UnionFind(h*w)
for y in range(h):
for x in range(w):
if C[y][x] == '#':
continue
for dy, dx in (-1, 0), (1, 0), (0, 1), (0, -1):
ny, nx = y+dy, x+dx
if 0 <= ny < h and 0 <= nx < w:
if C[ny][nx] != '#':
uf.Unite(y*w+x, ny*w+nx)
for y in range(h):
for x in range(w):
if C[y][x] != '#':
p = y*w+x
break
else:
continue
break
q = deque([])
dist = [[INF]*w for i in range(h)]
for y in range(h):
for x in range(w):
if C[y][x] == '#':
continue
if uf.Same(p, y*w+x):
q.append((y, x))
dist[y][x] = 0
while q:
y, x = q.popleft()
for dy, dx in (-1, 0), (1, 0), (0, 1), (0, -1):
ny, nx = y+dy, x+dx
if 0 <= ny < h and 0 <= nx < w:
if dist[ny][nx] == INF:
dist[ny][nx] = dist[y][x]+1
q.append((ny, nx))
ans = INF
for y in range(h):
for x in range(w):
if C[y][x] == '#':
continue
if not uf.Same(p, y*w+x):
ans = min(ans, dist[y][x]-1)
print(ans)
brthyyjp