Depth-first search (DFS) code in python

后端 未结 7 1430
暖寄归人
暖寄归人 2021-01-02 13:34

Can you please let me know what is incorrect in below DFS code. It\'s giving correct result AFAIK, but I don\'t know when it will fail.

graph1 = {
    \'A\'          


        
7条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-02 13:50

    Here's an iterative (non-recursive) implementation of a DFS:

    def dfs_iterative(graph, start_vertex):
        visited = set()
        traversal = []
        stack = [start_vertex]
        while stack:
            vertex = stack.pop()
            if vertex not in visited:
                visited.add(vertex)
                traversal.append(vertex)
                stack.extend(reversed(graph[vertex]))   # add vertex in the same order as visited
        return traversal
    
    test_graph = {
        'A' : ['B','S'],
        'B' : ['A'],
        'C' : ['D','E','F','S'],
        'D' : ['C'],
        'E' : ['C','H'],
        'F' : ['C','G'],
        'G' : ['F','S'],
        'H' : ['E','G'],
        'S' : ['A','C','G']
    }
    
    print(dfs_iterative(test_graph, 'A'))
    

    Output:

    ['A', 'B', 'S', 'C', 'D', 'E', 'H', 'G', 'F']

提交回复
热议问题