forked from prabhupant/python-ds
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDFS.py
More file actions
46 lines (33 loc) · 973 Bytes
/
Copy pathDFS.py
File metadata and controls
46 lines (33 loc) · 973 Bytes
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
# An Iterative DFS solution.
class Graph:
def __init__(self, V):
self.V = V
self.adj = [[] for i in range(V)]
def add_edge(self, v, w):
self.adj[v].append(w)
def DFS_util(self, s, visited):
stack = []
stack.append(s)
while (len(stack) != 0):
s = stack.pop()
if (not visited[s]):
print(s, end=" ")
visited[s] = True
i = 0
while i < len(self.adj[s]):
if (not visited[self.adj[s][i]]):
stack.append(self.adj[s][i])
i += 1
def DFS(self):
visited = [False] * self.V
for i in range(self.V):
if (not visited[i]):
self.DFS_util(i, visited)
if __name__ == '__main__':
g = Graph(5)
g.add_edge(1, 0)
g.add_edge(2, 1)
g.add_edge(3, 4)
g.add_edge(4, 0)
print("Following is Depth First Traversal")
g.DFS()