基于图的从头输出的深度优先遍历 --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]]

你可能感兴趣的:(编程)