【LeetCode】934. Shortest Bridge 解題報告(Python)
作者: 負雪明燭
id: fuxuemingzhu
個人部落格: http://fuxuemingzhu.cn/
目錄
題目地址:https://leetcode.com/problems/shortest-bridge/description/
題目描述
In a given 2D binary array A
, there are two islands. (An island is a 4-directionally connected group of 1
1
s.)
Now, we may change 0
s to 1
s so as to connect the two islands together to form 1
island.
Return the smallest number of 0
s that must be flipped. (It is guaranteed that the answer is at least 1.)
Example 1:
Input: [[0,1],[1,0]]
Output: 1
Example 2:
Input: [[0,1,0],[0,0,0],[0,0,1]] Output: 2
Example 3:
Input: [[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]]
Output: 1
Note:
1 <= A.length = A[0].length <= 100
A[i][j] == 0 or A[i][j] == 1
題目大意
題目給出一個二維矩陣,其中的0表示水,1表示陸地,四聯通的陸地會連成一片島。題目保證給出了兩個島,求兩個島之間的最短路徑。
解題方法
DFS + BFS
本週周賽第三題,比賽的時候沒時間寫了,但是賽後感覺這個題很簡單。
首先用DFS來確定其中一個島,把這個島所有的1變成了2,這麼做的目的是和另一個島作為區分。需要注意的是把找到的這個島的每個位置都新增到佇列裡面,我們會用這個佇列去做BFS.
找出了島之後,使用BFS,來找出這個島離1最近的距離是多少。每次迴圈是相當於走了一步,把所有走了一步仍然是水路的位置設定成2,並放到佇列裡;如果找到了1,就可以直接結束了,因為我們的BFS沒走一步會向前走一些,第一次尋找到的就是最近的距離;如果找到的是2,那說明這個位置已經遍歷過了,直接不要管了。
最壞時間複雜度是O(MN),最壞空間複雜度O(MN). 時間是240 ms。
class Solution:
def shortestBridge(self, A):
"""
:type A: List[List[int]]
:rtype: int
"""
M, N = len(A), len(A[0])
dirs = [(1, 0), (-1, 0), (0, 1), (0, -1)]
visited = [[0] * N for _ in range(M)]
hasfind = False
que = collections.deque()
for i in range(M):
if hasfind: break
for j in range(N):
if A[i][j] == 1:
self.dfs(A, i, j, visited, que)
hasfind = True
break
step = 0
while que:
size = len(que)
for _ in range(size):
i, j = que.popleft()
for d in dirs:
x, y = i + d[0], j + d[1]
if 0 <= x < M and 0 <= y < N:
visited[x][y] = 1
if A[x][y] == 1:
return step
elif A[x][y] == 0:
A[x][y] = 2
que.append((x, y))
else:
continue
step += 1
return -1
def dfs(self, A, i, j, visited, que):
if visited[i][j]: return
visited[i][j] = 1
M, N = len(A), len(A[0])
dirs = [(1, 0), (-1, 0), (0, 1), (0, -1)]
if A[i][j] == 1:
que.append((i, j))
A[i][j] = 2
for d in dirs:
x, y = i + d[0], j + d[1]
if 0 <= x < M and 0 <= y < N:
self.dfs(A, x, y, visited, que)
相似題目
參考資料
日期
2018 年 11 月 4 日 —— 下雨的週日