File tree Expand file tree Collapse file tree 1 file changed +59
-0
lines changed
Expand file tree Collapse file tree 1 file changed +59
-0
lines changed Original file line number Diff line number Diff line change 1+ from collections import defaultdict
2+
3+ # This class represents a directed graph using
4+ # adjacency list representation
5+ class Graph :
6+
7+ # Constructor
8+ def __init__ (self ):
9+
10+ # Default dictionary to store graph
11+ self .graph = defaultdict (list )
12+
13+
14+ # Function to add an edge to graph
15+ def addEdge (self , u , v ):
16+ self .graph [u ].append (v )
17+
18+
19+ # A function used by DFS
20+ def DFSUtil (self , v , visited ):
21+
22+ # Mark the current node as visited
23+ # and print it
24+ visited .add (v )
25+ print (v , end = ' ' )
26+
27+ # Recur for all the vertices
28+ # adjacent to this vertex
29+ for neighbour in self .graph [v ]:
30+ if neighbour not in visited :
31+ self .DFSUtil (neighbour , visited )
32+
33+
34+ # The function to do DFS traversal. It uses
35+ # recursive DFSUtil()
36+ def DFS (self , v ):
37+
38+ # Create a set to store visited vertices
39+ visited = set ()
40+
41+ # Call the recursive helper function
42+ # to print DFS traversal
43+ self .DFSUtil (v , visited )
44+
45+
46+ # Driver's code
47+ if __name__ == "__main__" :
48+ g = Graph ()
49+ g .addEdge (0 , 1 )
50+ g .addEdge (0 , 2 )
51+ g .addEdge (1 , 2 )
52+ g .addEdge (2 , 0 )
53+ g .addEdge (2 , 3 )
54+ g .addEdge (3 , 3 )
55+
56+ print ("Following is Depth First Traversal (starting from vertex 2)" )
57+
58+ # Function call
59+ g .DFS (2 )
You can’t perform that action at this time.
0 commit comments