leetcode回顾——[934] Shortest Bridge

题目

在给定的二维二进制数组 A 中,存在两座岛。(岛是由四面相连的 1 形成的一个最大组。)

现在,我们可以将 0 变为 1,以使两座岛连接起来,变成一座岛。

返回必须翻转的 0 的最小数目。(可以保证答案至少是 1。)

示例 1:

输入:[[0,1],[1,0]]
输出:1
示例 2:

输入:[[0,1,0],[0,0,0],[0,0,1]]
输出:2
示例 3:

输入:[[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]]
输出:1

提示:

1 <= A.length = A[0].length <= 100
A[i][j] == 0 或 A[i][j] == 1

题解

  • 根据题目可知,要求桥的最短长度,那么就用广度优先搜索的方法
  • 是求两座岛屿之间的桥的最短长度,那么就可以先把一座岛先找出来,把这个岛的所有坐标放入一个队列中,然后用这个队列去进行BFS,每一轮BFS,就将distance + 1,当发现某个点的隔壁就是另一座岛屿时,计算此时的桥长度与当前桥的最短长度进行取最小值
  • 循环结束后,得到桥的最短长度

AC代码

该AC代码的效率不高,还不是最优的解法!

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
54
55
56
from collections import deque

class Solution(object):
def shortestBridge(self, A):
"""
:type A: List[List[int]]
:rtype: int
"""
have_find = False
first_island = deque()
for i in range(len(A)):
for j in range(len(A[0])):
if A[i][j] == 1:
self.dfs(grid=A, x=i, y=j, first_island=first_island)
have_find = True
break
if have_find:
break
distance = 2
ans = len(A) * len(A[0])
while first_island:
l = len(first_island)
for i in range(l):
x, y = first_island.popleft()
for dir_x, dir_y in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
n_x, n_y = x + dir_x, y + dir_y
if self.judge(n_x, n_y, A):
if A[n_x][n_y] == 1:
ans = min(ans, abs(A[x][y]) - 1)
elif A[n_x][n_y] != 0:
A[n_x][n_y] = -1 * abs(A[n_x][n_y])
else:
A[n_x][n_y] = distance
if (n_x, n_y) not in first_island:
first_island.append((n_x, n_y))
distance += 1
return ans

def dfs(self, grid, x, y, first_island):
if x >= 0 and x < len(grid) and y >= 0 and y < len(grid[0]):
if grid[x][y] == 1:
grid[x][y] = -1
first_island.append((x, y))
self.dfs(grid, x - 1, y, first_island)
self.dfs(grid, x + 1, y, first_island)
self.dfs(grid, x, y - 1, first_island)
self.dfs(grid, x, y + 1, first_island)

def judge(self, x, y, grid):
return x >= 0 and x < len(grid) and y >= 0 and y < len(grid[0])


if __name__ == '__main__':
s = Solution()
A = [[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(s.shortestBridge(A=A))