bfs,同时使用队列。对比dfs,使用栈。
from collections import deque
def land(matrix):
length=len(matrix) #数组行数
width=len(matrix[0]) #数组列数
re=[[0 for _ in range(width)] for _ in range(length)]
print(re)
direction=[[1,0],[-1,0],[0,1],[0,-1]]
queue=deque([])
for i in range(length):
for j in range(width):
if matrix[i][j]==1:
#如果是岛(1表示岛)
re[i][j]=0 #自己和自己距离为0
queue.append((i,j)) #将岛屿的位置存入queue
else:
re[i][j]=-1 #其他值先设置为-1
while queue:
x,y=queue.popleft() #弹出一个坐标
for d in direction:
x1=x+d[0]
y1=y+d[1]
if x1>=0 and y1>=0 and x1<length and y1<length and re[x1][y1]==-1: #在数组范围内,且值为-1
re[x1][y1]=re[x][y]+1 #re[x1][y1]是re[x][y]的邻接
queue.append((x1,y1))
return re
matrix1=[[0,0,0],
[0,1,1],
[0,0,0]]
matrix2=[[1,1,0],
[1,0,0],
[2,1,0]]
print(land(matrix1))
浙公网安备 33010602011771号