LeetCode 934. Shortest Bridge
考点 | 难度 |
---|---|
Matrix | Medium |
题目
You are given an n x n binary matrix grid where 1 represents land and 0 represents water.
An island is a 4-directionally connected group of 1’s not connected to any other 1’s. There are exactly two islands in grid.
You may change 0’s to 1’s to connect the two islands to form one island.
Return the smallest number of 0’s you must flip to connect the two islands.
思路
1 先用dfs找出第一个island的所有坐标,保存到stack里
2 对于stack里的每个坐标,检查它的四个方向有没有1,如果找到1返回step = 1,如果没有就把这个坐标对应的值改掉,并且储存到一个新的list里(不是原来的stack)
3 当原来的stack全部被iterate完但是没有找到1,step + 1,iterate这个循环里create的新的list
4 以此类推直到找到1
答案
class Solution:
def shortestBridge(self, A: List[List[int]]) -> int:
found = False
stack = []
n, m = len(A), len(A[0])
# find the first island
for i in range(n):
for j in range(m):
if A[i][j]:
# using depth first search to find all connected ('1') locations
# since there are only two islands
# we only need to find the first one
self.dfs(A, i, j, n, m, stack)
found = True
break
if found:
break
steps = 0
# breadth first search, once we find next '1', that is our final answer
dirs = [(0, 1), (0, -1), (1, 0), (-1, 0)]
while stack:
size = len(stack)
level = []
while(size):
temp = stack.pop()
size-=1
x, y = temp[0], temp[1]
for dx, dy in dirs:
tx = x+dx
ty = y+dy
if tx<0 or ty<0 or tx>=n or ty>=m or A[tx][ty]==2:
continue
if A[tx][ty]==1:
return steps
A[tx][ty]=2
level.append((tx, ty))
steps+=1
stack = level
return -1
def dfs(self, A, row, col, n, m, stack):
# we only need to find connected '1's
# we need A[row][col]==1\
if row<0 or col<0 or row>=n or col>=m or A[row][col]!=1:
return
A[row][col]=2
# use stack for breath first search
stack.append((row, col))
self.dfs(A, row+1, col, n, m, stack)
self.dfs(A, row-1, col, n, m, stack)
self.dfs(A, row, col+1, n, m, stack)
self.dfs(A, row, col-1, n, m, stack)