图的广度优先遍历,采用队列(queue)实现 ,先进先出
graph={
"A":["B","C"],
"B":["A","C","D"],
"C":["A","B","D","E"],
"D":["B","C","E","F"],
"E":["C","D"],
"F":["D"]
}#用字典建立一个图
def BFS(graph,s):
queue=[]
queue.append(s)
seen=set()
seen.add(s)
while(len(queue)>0):
vertex=queue.pop(0)
nodes=graph[vertex]#邻接点
for n in nodes:
if n not in seen:
queue.append(n)
seen.add(n)
print(vertex)
BFS(graph,"A")
可用于求最短路径,此处为A-D,运用邻接表
def BFS(graph,s):
queue=[]
queue.append(s)
seen=set()
seen.add(s)
parent={s:None}
while(len(queue)>0):
vertex=queue.pop(0)
nodes=graph[vertex]#邻接点
for n in nodes:
if n not in seen:
queue.append(n)
seen.add(n)
parent[n]=vertex#vertex相当于根节点
return parent
parent=BFS(graph,"D")
v="A"
while v!=None:
print(v)
v=parent[v]
图的深度优先遍历,用栈(stack)实现
def DFS(graph,s):
stack=[]
stack.append(s)
seen=set()
seen.add(s)
while(len(stack)>0):
vertex=stack.pop()
nodes=graph[vertex]#邻接点
for n in nodes:
if n not in seen:
stack.append(n)
seen.add(n)
print(vertex)
DFS(graph,"A")
可改为随机选择路径
import random
#将for n in nodes改为
for n in random.sample(nodes,len(nodes)):