首页 > 编程语言 > 详细

DFS-python

时间:2022-05-27 20:13:01      阅读:15      评论:0      收藏:0      [点我收藏+]
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):
    stack=[]                         #将BFS中的queue全部改成stack
    stack.append(s)
    seen=set()
    seen.add(s)
    while(len(stack)>0):
        vertex=stack.pop()       #后进先出,弹出末尾
        nodes=graph[vertex]
        for w in nodes:
            if w not in seen:
                seen.add(w)
                stack.append(w)
        print(vertex)

BFS(graph,"A")

根据BFS写出一个DFS的算法,只改动了几步即可使用

DFS-python

原文:https://www.cnblogs.com/CCCDD/p/15335177.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!