-
Notifications
You must be signed in to change notification settings - Fork 0
/
shortest-bridge.py
39 lines (36 loc) · 1.42 KB
/
shortest-bridge.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class Solution(object):
def shortestBridge(self, A):
R, C = len(A), len(A[0])
def neighbors(r, c):
for nr, nc in ((r-1,c),(r,c-1),(r+1,c),(r,c+1)):
if 0 <= nr < R and 0 <= nc < C:
yield nr, nc
def get_components():
done = set()
components = []
for r, row in enumerate(A):
for c, val in enumerate(row):
if val and (r, c) not in done:
# Start dfs
stack = [(r, c)]
seen = {(r, c)}
while stack:
node = stack.pop()
for nei in neighbors(*node):
if A[nei[0]][nei[1]] and nei not in seen:
stack.append(nei)
seen.add(nei)
done |= seen
components.append(seen)
return components
source, target = get_components()
print source, target
queue = collections.deque([(node, 0) for node in source])
done = set(source)
while queue:
node, d = queue.popleft()
if node in target: return d-1
for nei in neighbors(*node):
if nei not in done:
queue.append((nei, d+1))
done.add(nei)