Depth-first search (DFS) code in python

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

    from collections import defaultdict
    
    class Graph:
        def __init__(self):
            self.graph = defaultdict(list)
    
        def addEdge(self,u,v):
            self.graph[u].append(v)
    
        def DFS(self,v,vertex):
            visited = [False]*vertex
            print(self. graph)
            # print(len(self.graph),"+++")
            self.DFSUtil(v,visited)
    
        def DFSUtil(self,v,visited):
            visited[v]=True
            print(v)
    
            for i in self.graph[v]:
                if visited[i] == False:
                    # print(visited)
                    self.DFSUtil(i,visited)
    g= Graph()
    
    vertex=7
    
    g.addEdge(0,1)
    g.addEdge(0,2)
    g.addEdge(0,6)
    g.addEdge(0,5)
    g.addEdge(5,3)
    g.addEdge(5,4)
    g.addEdge(4,3)
    g.addEdge(6,4)
    
    g.DFS(0,vertex) 
    

    This is the modification for the above code because that doesn't work with in all cases.
    We have to specify the number of vectors and then give edges manually.

提交回复
热议问题