Depth-first search (DFS) code in python

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

    Here is a more versatile algorithm, the one asked in the question works only for undirected graphs. But this hopefully works for both them. Check it out

    graph1= {
    'A' : ['B','S'],
    'B' : [],
    'C' : ['E','S'],
    'D' : ['C'],
    'E' : ['H'],
    'F' : ['C'],
    'G' : ['F','S'],
    'H' : ['G'],
    'S' : []
    }
    visited = []
    
    def dfs_visit(graph, s):
        global visited
        for v in graph[s]:
            if v not in visited:
                visited.append(v)
                dfs_visit(graph, v)
    
    
    def dfs(graph):
        global visited
        for v in [*graph]:
            if v not in visited:
                visited.append(v)
                dfs_visit(graph,v)
    
    dfs(graph1)
    print(visited)
    

提交回复
热议问题