trying to find all the path in a graph using DFS recursive in Python

后端 未结 2 563
耶瑟儿~
耶瑟儿~ 2021-01-16 04:34

I have found a solution that was posted some times ago and I have tried to apply it to my exercise but it doesn\'t work. I have a class graph that has nodes and edges and a

2条回答
  •  有刺的猬
    2021-01-16 05:07

    Since you only want to get all paths from start to end, the path is appended to your total path list when it reaches the end. The total list of paths is not returned but rather populated:

    paths = []
    
    def myDFS(graph,start,end,path=[]): 
        path=path+[start] 
        if start==end:
            paths.append(path) 
        for node in graph.childrenOf(start):
            if node not in path:
                myDFS(graph,node,end,path)
    

提交回复
热议问题