Depth-first search (DFS) code in python

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

    I think you have an indentation problem there. Assuming your code looks like this:

    graph1 = {
        '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']
    }
    
    visited = []
    
    def dfs(graph,node):
        global visited
        if node not in visited:
            visited.append(node)
            for n in graph[node]:
                dfs(graph,n)
    
    dfs(graph1,'A')
    print(visited)
    

    I would say a couple of things:

    • Avoid globals if you can
    • Instead of a list for visited, use a set

    plus:

    • This will not work for forests but I assume you already know that
    • It will fail if you reference a node that does not exist.

    Updated code:

    graph1 = {
        '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']
    }
    
    def dfs(graph, node, visited):
        if node not in visited:
            visited.append(node)
            for n in graph[node]:
                dfs(graph,n, visited)
        return visited
    
    visited = dfs(graph1,'A', [])
    print(visited)
    
    0 讨论(0)
提交回复
热议问题