BFS DFS Python 实现
BFS 和DFS在Python实现上一个是用Queue,pop(0)顺序打印出首结点,一个是用Stack, pop()顺序打印出尾结点。#!/usr/bin/python# -*- coding: utf-8 -*-def BFS(start, graph):queue=[]visit=[]queue.append(start)visit.append(start)while queue:node
·
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
更多推荐
已为社区贡献1条内容
所有评论(0)