1.BFS 广度优先搜索
利用队列,先进先出原理
graph={
'A':['B','D','G'],
'B':['E','A','F'],
'D':['A','F'],
'E':['B','G'],
'F':['B','D','C'],
'C':['H','F'],
'G':['E','A'],
'H':['C']
}
def Bfs(graph,s):
stack=[s]
visted=set()
visted.add(s)
ans=[]
while stack:
vertex=stack.pop(0)
ans.append(vertex)
for node in graph[vertex]:
if node not in visted:
stack.append(node)
visted.add(node)
return ans
Bfs(graph,'A')
结果:
['A', 'B', 'D', 'G', 'E', 'F', 'C', 'H']
2.深度优先搜索
def dfs(graph,s): #栈
stack=[s]
ans=[]
visted=set(s)
while stack:
vertex=stack.pop()
if vertex not in ans:ans.append(vertex)
visted.add(vertex)
for node in graph[vertex]:
if node not in visted :
stack.append(node)
print(stack)
return ans
dfs(graph,'A')
['A', 'G', 'E', 'B', 'F', 'C', 'H', 'D']
例题:图像渲染
解法1:深度优先搜索,利用栈 先进后出
def floodFill(image, sr: int, sc: int, color: int): #利用栈 进行深度优先搜索
dirs=[
lambda x,y:(x-1,y),#上
lambda x,y:(x+1,y),#下
lambda x,y:(x,y-1),#左
lambda x,y:(x,y+1),#右
] #设置方向
n=len(image)
m=len(image[0])
stack=[(sr,sc)]
val=image[sr][sc]
image[sr][sc]=color
while stack:
cur=stack[-1]
for dir in dirs:
nex=dir(cur[0],cur[1])
if nex[0]>=0 and nex[0]<n and nex[1]>=0 and nex[1]<m and image[nex[0]][nex[1]]==val:
# print(nex)
stack.append(nex)
image[nex[0]][nex[1]]=color
break
else: #注意这个else,记得回退
stack.pop()
for i in image:print(i)
# return image
image = [[1,1,1],[1,1,0],[1,0,1]]
image1 = [[0,0,0],[0,0,0]]
floodFill(image1,0,0,2)
解法2:广度优先算法,利用队列,先进先出
def floodFill(image, sr: int, sc: int, color: int):
dirs=[
lambda x,y:(x-1,y),#上
lambda x,y:(x+1,y),#下
lambda x,y:(x,y-1),#左
lambda x,y:(x,y+1),#右
]
n=len(image)
m=len(image[0])
stack=[(sr,sc)]
val=image[sr][sc]
image[sr][sc]=color
while stack:
cur=stack.pop(0)
for dir in dirs:
nex=dir(cur[0],cur[1])
if nex[0]>=0 and nex[0]<n and nex[1]>=0 and nex[1]<m and image[nex[0]][nex[1]]==val:
stack.append(nex)
image[nex[0]][nex[1]]=color
for i in image:print(i)
# return image
image = [[1,1,1],[1,1,0],[1,0,1]]
image1 = [[0,0,0],[0,0,0]]
floodFill(image1,0,0,2)