1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > python 广度优先算法和深度优先算法遍历的实现

python 广度优先算法和深度优先算法遍历的实现

时间:2019-06-17 01:19:50

相关推荐

python 广度优先算法和深度优先算法遍历的实现

用这个图为例子

用字典存储这个图

graph = {'A':['C','B'],'B':['A','C','D'],'C':['A','B','E','D'],'D':['B','C','E','F'],'E':['C','D'],'F':['D']}

广度优先算法的本质是一个队列

def BFS(graph,start):queue = []queue.append(start)seen = set()seen.add(start)while len(queue)>0:vert = queue.pop(0)# 这里表现出是个队列,先进先出nodes = graph[vert]for w in nodes:if w not in seen:queue.append(w)seen.add(w)print(vert)BFS(graph,'D')

深度优先算法的本质是一个堆栈

def DFS(graph,start):queue = []queue.append(start)seen = set()seen.add(start)while len(queue)>0:vert = queue.pop()# 这里表现出是一个堆栈 ,后进先出nodes = graph[vert]for w in nodes:if w not in seen:queue.append(w)seen.add(w)print(vert)DFS(graph,'A')

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。