BFS 和DFS在Python实现上一个是用Queue,pop(0)顺序打印出首结点,一个是用Stack, pop()顺序打印出尾结点。
def BFS(start, graph):
queue=[]
visit=[]
queue.append(start)
visit.append(start)
while queue:
node=queue.pop(0)
nodes=graph[node]
for i in nodes:
if i not in visit:
queue.append(i)
visit.append(i)
print(node, end='\t')
def DFS(start, graph):
stack=[]
visit=[]
stack.append(start)
visit.append(start)
while stack:
node=stack.pop()
nodes=graph[node]
for i in nodes:
if i not in visit:
stack.append(i)
visit.append(i)
print(node, end='\t')
if __name__ == "__main__":
graph = {
'A' : ['B','C','D'],
'B' : ['A','E','F'],
'C' : ['A','D','F','G'],
'D' : ['A','C','G'],
'E' : ['B'],
'F' : ['B','C'],
'G' : ['C','D']
}
print("BFS search result:")
BFS('A',graph)
print('\n')
print("DFS search result:")
DFS('A',graph)
运行结果:
BFS search result:
A B C D E F G
DFS search result:
A D G C F B E
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)