forked from seeditsolution/pythonprogram
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dfsTraversal
51 lines (25 loc) · 802 Bytes
/
dfsTraversal
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
from collections import defaultdict
class Graph:
def __init__(self):
self.graph = defaultdict(list)
def addEdge(self, u, v):
self.graph[u].append(v)
def DFSUtil(self, v, visited):
visited[v] = True
print(v, end = ' ')
for i in self.graph[v]:
if visited[i] == False:
self.DFSUtil(i, visited)
def DFS(self, v):
visited = [False] * (max(self.graph)+1)
self.DFSUtil(v, visited)
# Create a graph given
g = Graph()
g.addEdge(0, 1)
g.addEdge(0, 2)
g.addEdge(1, 2)
g.addEdge(2, 0)
g.addEdge(2, 3)
g.addEdge(3, 3)
print("Following is DFS from (starting from vertex 2)")
g.DFS(2)