版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zjucor/article/details/83714072
In a given 2D binary array A
, there are two islands. (An island is a 4-directionally connected group of 1
s not connected to any other 1s.)
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
orA[i][j] == 1
思路:2遍BFS,第一次先求出2个group,第二次遍历某个group到另外一个group的最短距离
class Solution:
def shortestBridge(self, A):
"""
:type A: List[List[int]]
:rtype: int
"""
n,m=len(A),len(A[0])
for i in range(n):
for j in range(m):
if A[i][j]==1: break
if A[i][j]==1: break
ds=[[0,1],[0,-1],[1,0],[-1,0]]
A[i][j]=2
q=[(i,j)]
while q:
si,sj=q.pop()
for di,dj in ds:
ii,jj=si+di,sj+dj
if 0<=ii<n and 0<=jj<m and A[ii][jj]==1:
A[ii][jj]=2
q.append((ii,jj))
q=[(i,j) for i in range(n) for j in range(m) if A[i][j]==2]
qq=[]
vis=[[False for _ in range(m)] for _ in range(n)]
for i,j in q: vis[i][j]=True
step=0
while q:
while q:
si,sj=q.pop()
for di,dj in ds:
ii,jj=si+di,sj+dj
if 0<=ii<n and 0<=jj<m:
if A[ii][jj]==1: return step
if A[ii][jj]==0 and not vis[ii][jj]:
vis[ii][jj]=True
qq.append((ii,jj))
q,qq=qq,q
step+=1