File tree Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Original file line number Diff line number Diff line change
1
+
2
+ from collections import defaultdict
3
+
4
+ class Graph:
5
+
6
+
7
+ def __init__(self):
8
+
9
+
10
+ self.graph = defaultdict(list)
11
+
12
+
13
+ def addEdge(self, u, v):
14
+ self.graph[u].append(v)
15
+
16
+
17
+ def DFSUtil(self, v, visited):
18
+
19
+
20
+ visited[v] = True
21
+ print(v, end = ' ')
22
+
23
+
24
+ for i in self.graph[v]:
25
+ if visited[i] == False:
26
+ self.DFSUtil(i, visited)
27
+
28
+
29
+ def DFS(self, v):
30
+
31
+
32
+ visited = [False] * (max(self.graph)+1)
33
+
34
+
35
+ self.DFSUtil(v, visited)
36
+
37
+
38
+
39
+ # Create a graph given
40
+
41
+ g = Graph()
42
+ g.addEdge(0, 1)
43
+ g.addEdge(0, 2)
44
+ g.addEdge(1, 2)
45
+ g.addEdge(2, 0)
46
+ g.addEdge(2, 3)
47
+ g.addEdge(3, 3)
48
+
49
+ print("Following is DFS from (starting from vertex 2)")
50
+ g.DFS(2)
51
+
You can’t perform that action at this time.
0 commit comments