Skip to content

Commit c0da475

Browse files
committed
Depth First Search Graph Traversal
1 parent 18444bf commit c0da475

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

Graph/P02_DepthFirstSearch.py

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
# Author: OMKAR PATHAK
2+
3+
class Graph():
4+
def __init__(self):
5+
self.vertex = {}
6+
7+
# for printing the Graph vertexes
8+
def printGraph(self):
9+
for i in self.vertex.keys():
10+
print(i,' -> ', ' -> '.join([str(j) for j in self.vertex[i]]))
11+
12+
# for adding the edge beween two vertexes
13+
def addEdge(self, fromVertex, toVertex):
14+
# check if vertex is already present,
15+
if fromVertex in self.vertex.keys():
16+
self.vertex[fromVertex].append(toVertex)
17+
else:
18+
# else make a new vertex
19+
self.vertex[fromVertex] = [toVertex]
20+
21+
def DFS(self):
22+
# visited array for storing already visited nodes
23+
visited = [False] * len(self.vertex)
24+
25+
# call the recursive helper function
26+
for i in range(len(self.vertex)):
27+
if visited[i] == False:
28+
self.DFSRec(i, visited)
29+
30+
def DFSRec(self, startVertex, visited):
31+
# mark start vertex as visited
32+
visited[startVertex] = True
33+
34+
print(startVertex, end = ' ')
35+
36+
# Recur for all the vertexes that are adjacent to this node
37+
for i in self.vertex[startVertex]:
38+
if visited[i] == False:
39+
self.DFSRec(i, visited)
40+
41+
if __name__ == '__main__':
42+
g = Graph()
43+
g.addEdge(0, 1)
44+
g.addEdge(0, 2)
45+
g.addEdge(1, 2)
46+
g.addEdge(2, 0)
47+
g.addEdge(2, 3)
48+
g.addEdge(3, 3)
49+
50+
g.printGraph()
51+
print('DFS:')
52+
g.DFS()
53+
54+
# OUTPUT:
55+
# 0  ->  1 -> 2
56+
# 1  ->  2
57+
# 2  ->  0 -> 3
58+
# 3  ->  3
59+
# DFS:
60+
# 0 1 2 3

0 commit comments

Comments
 (0)