-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path0934-shortest-bridge.py
More file actions
53 lines (44 loc) · 1.74 KB
/
0934-shortest-bridge.py
File metadata and controls
53 lines (44 loc) · 1.74 KB
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# time complexity: O(n^2)
# space complexity: O(n^2)
from typing import List
class Solution:
def shortestBridge(self, grid: List[List[int]]) -> int:
n = len(grid)
firstR, firstC = -1, -1
for r in range(n):
for c in range(n):
if grid[r][c] == 1:
firstR, firstC = r, c
break
bfsQueue = [(firstR, firstC)]
secondBfsQueue = [(firstR, firstC)]
grid[firstR][firstC] = 2
while bfsQueue:
newBfs = []
for x, y in bfsQueue:
for curR, curC in [(x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)]:
if 0 <= curR < n and 0 <= curC < n and grid[curR][curC] == 1:
newBfs.append((curR, curC))
secondBfsQueue.append((curR, curC))
grid[curR][curC] = 2
bfsQueue = newBfs
distance = 0
while secondBfsQueue:
newBfs = []
for x, y in secondBfsQueue:
for curR, curC in [(x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)]:
if 0 <= curR < n and 0 <= curC < n:
if grid[curR][curC] == 1:
return distance
elif grid[curR][curC] == 0:
newBfs.append((curR, curC))
grid[curR][curC] = -1
secondBfsQueue = newBfs
distance += 1
grid = [[0, 1], [1, 0]]
print(Solution().shortestBridge(grid))
grid = [[0, 1, 0], [0, 0, 0], [0, 0, 1]]
print(Solution().shortestBridge(grid))
grid = [[1, 1, 1, 1, 1], [1, 0, 0, 0, 1], [
1, 0, 1, 0, 1], [1, 0, 0, 0, 1], [1, 1, 1, 1, 1]]
print(Solution().shortestBridge(grid))