基于图的从头输出的深度优先遍历python
作者:互联网
class DFS:
def __init__(self, start):
self.path = [start]
self.path_list = []
def func(self, graph, node):
if node not in graph.keys():
print(self.path)
path = copy.deepcopy(self.path)
self.path_list.append(path)
else:
for item in graph[node]:
self.path.append(item)
self.func(graph, item)
self.path.pop() # 弹出最后一个元素
if __name__ == '__main__':
reaction_graph = {1: [2, 3], 2: [3, 4, 5], 3: [6, 7], 4: [8]}
dfs = DFS(1)
dfs.func(reaction_graph, 1)
print(dfs.path_list)
[1, 2, 3, 6]
[1, 2, 3, 7]
[1, 2, 4, 8]
[1, 2, 5]
[1, 3, 6]
[1, 3, 7]
[[1, 2, 3, 6], [1, 2, 3, 7], [1, 2, 4, 8], [1, 2, 5], [1, 3, 6], [1, 3, 7]]
标签:__,node,遍历,python,graph,self,dfs,path,从头 来源: https://blog.csdn.net/weixin_43236007/article/details/104411384