Depth-first search (DFS) code in python

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

     graph = {'A': ['B', 'C'],
             'B': ['A', 'D', 'E'],
             'C': ['A', 'F'],
             'D': ['B'],
             'E': ['B', 'F'],
             'F': ['C', 'E']}
    
       def dfs(s,d):
        def dfs_helper(s,d):
            if s == d:
                return True
            if  s in visited :
                return False
            visited.add(s)
            for c in graph[s]:
                dfs_helper(c,d)
            return False
        visited = set()
        return dfs_helper(s,d) 
    dfs('A','E') ---- True
    dfs('A','M') ---- False
    

提交回复
热议问题