Tracing and Returning a Path in Depth First Search

前端 未结 4 1955
青春惊慌失措
青春惊慌失措 2021-01-30 09:19

So I have a problem that I want to use depth first search to solve, returning the first path that DFS finds. Here is my (incomplete) DFS function:

    start = pr         


        
4条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-30 09:35

    Not specific to your problem, but you can tweak this code and apply it to different scenarios, in fact, you can make the stack also hold the path.

    Example:

         A
       /    \
      C      B
      \     / \
       \    D E
        \    /
           F
    
    
    graph = {'A': set(['B', 'C']),
             'B': set(['A', 'D', 'E']),
             'C': set(['A', 'F']),
             'D': set(['B']),
             'E': set(['B', 'F']),
             'F': set(['C', 'E'])}
    
    
    
    
    def dfs_paths(graph, start, goal):
        stack = [(start, [start])]
        visited = set()
        while stack:
            (vertex, path) = stack.pop()
            if vertex not in visited:
                if vertex == goal:
                    return path
                visited.add(vertex)
                for neighbor in graph[vertex]:
                    stack.append((neighbor, path + [neighbor]))
    
    print (dfs_paths(graph, 'A', 'F'))   #['A', 'B', 'E', 'F']
    

提交回复
热议问题