File tree Expand file tree Collapse file tree 1 file changed +89
-0
lines changed Expand file tree Collapse file tree 1 file changed +89
-0
lines changed Original file line number Diff line number Diff line change
1
+ # Python program to print DFS traversal for complete graph
2
+
3
+ from collections import defaultdict
4
+
5
+
6
+ # This class represents a directed graph using adjacency
7
+ # list representation
8
+
9
+ class Graph:
10
+
11
+
12
+
13
+ # Constructor
14
+
15
+ def __init__(self):
16
+
17
+
18
+
19
+ # default dictionary to store graph
20
+
21
+ self.graph = defaultdict(list)
22
+
23
+
24
+
25
+ # function to add an edge to graph
26
+
27
+ def addEdge(self,u,v):
28
+
29
+ self.graph[u].append(v)
30
+
31
+
32
+
33
+ # A function used by DFS
34
+
35
+ def DFSUtil(self, v, visited):
36
+
37
+
38
+
39
+ # Mark the current node as visited and print it
40
+
41
+ visited[v]= True
42
+
43
+ print v,
44
+
45
+
46
+
47
+ # Recur for all the vertices adjacent to
48
+
49
+ # this vertex
50
+
51
+ for i in self.graph[v]:
52
+
53
+ if visited[i] == False:
54
+
55
+ self.DFSUtil(i, visited)
56
+
57
+
58
+
59
+
60
+
61
+ # The function to do DFS traversal. It uses
62
+
63
+ # recursive DFSUtil()
64
+
65
+ def DFS(self):
66
+
67
+ V = len(self.graph) #total vertices
68
+
69
+
70
+
71
+ # Mark all the vertices as not visited
72
+
73
+ visited =[False]*(V)
74
+
75
+
76
+
77
+ # Call the recursive helper function to print
78
+
79
+ # DFS traversal starting from all vertices one
80
+
81
+ # by one
82
+
83
+ for i in range(V):
84
+
85
+ if visited[i] == False:
86
+
87
+ self.DFSUtil(i, visited)
88
+
89
+
You can’t perform that action at this time.
0 commit comments