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的算法,只改动了几步即可使用
原文:https://www.cnblogs.com/CCCDD/p/15335177.html