Depth-first search (DFS) code in python

后端 未结 7 1457
暖寄归人
暖寄归人 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:49

    Without recursion:

    def dfs(graph, node):
        visited = [node]
        stack = [node]
        while stack:
            node = stack[-1]
            if node not in visited:
                visited.extend(node)
            remove_from_stack = True
            for next in graph[node]:
                if next not in visited:
                    stack.extend(next)
                    remove_from_stack = False
                    break
            if remove_from_stack:
                stack.pop()
        return visited
    
    print (dfs(graph1, 'A'))
    

    Output:

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

提交回复
热议问题