leetcode 934 最短桥

题目:
In a given 2D binary array A, there are two islands. (An island is a 4-directionally connected group of 1s not connected to any other 1s.)

Now, we may change 0s to 1s so as to connect the two islands together to form 1 island.

Return the smallest number of 0s 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之外的值即可,这里我把它的值置为-1,然后把这个岛的每一块所在的坐标存进一个序列里面,然后进行广度搜索,当其中一个坐标相邻位置为1:即当前的岛已经扩张到了另外一个岛的边界,这个时候已经可以终止搜索了,直接返回步数即可
总结上面的思路过程:
通过深度优先搜索找其中一个岛,并且将其进行标记,使得整块大陆被划分为三块:第一个岛(其中每一块都用-1来进行表示),海洋(0表示),另外一个岛(每一块都用1来表示),然后在第一个岛的边缘进行扩张,每次扩张一圈,并且把这个圈的坐标加入到队列中,搜索终止条件:这个圈其中任何一个位置已经和另外一个岛的边缘相邻
class Solution(object):
def shortestBridge(self, A):
“”"
:type A: List[List[int]]
:rtype: int
“”"
def dfs(i,j):
A[i][j]=-1
bfs.append((i,j))
for x,y in ((i+1,j),(i-1,j),(i,j-1),(i,j+1)):
if 0<=x<n and 0<=y<n and A[x][y]==1:
dfs(x,y)
def first():
for i in range(n):
for j in range(n):
if A[i][j]:
return i,j
n,step,bfs=len(A),0,[]
dfs(*first())
while bfs:
new=[]
for i,j in bfs:
for x,y in ((i+1,j),(i-1,j),(i,j-1),(i,j+1)):
if 0<=x<n and 0<=y<n:
if A[x][y]==1:
return step
elif not A[x][y]:
A[x][y]=-1
new.append((x,y))
step,bfs=step+1,new

猜你喜欢

转载自blog.csdn.net/weixin_44482648/article/details/86576502