Python/graphs/depth_first_search.py

66 lines
1.6 KiB
Python
Raw Normal View History

2018-10-19 12:48:28 +00:00
#!/usr/bin/python
""" Author: OMKAR PATHAK """
2019-10-05 05:14:13 +00:00
class Graph:
2018-10-19 12:48:28 +00:00
def __init__(self):
self.vertex = {}
# for printing the Graph vertices
2018-10-19 12:48:28 +00:00
def printGraph(self):
print(self.vertex)
for i in self.vertex.keys():
2019-10-05 05:14:13 +00:00
print(i, " -> ", " -> ".join([str(j) for j in self.vertex[i]]))
2018-10-19 12:48:28 +00:00
# for adding the edge between two vertices
2018-10-19 12:48:28 +00:00
def addEdge(self, fromVertex, toVertex):
# check if vertex is already present,
if fromVertex in self.vertex.keys():
self.vertex[fromVertex].append(toVertex)
else:
# else make a new vertex
self.vertex[fromVertex] = [toVertex]
def DFS(self):
# visited array for storing already visited nodes
visited = [False] * len(self.vertex)
# call the recursive helper function
for i in range(len(self.vertex)):
if visited[i] == False:
self.DFSRec(i, visited)
def DFSRec(self, startVertex, visited):
# mark start vertex as visited
visited[startVertex] = True
2019-10-05 05:14:13 +00:00
print(startVertex, end=" ")
2018-10-19 12:48:28 +00:00
# Recur for all the vertices that are adjacent to this node
2018-10-19 12:48:28 +00:00
for i in self.vertex.keys():
if visited[i] == False:
self.DFSRec(i, visited)
2019-10-05 05:14:13 +00:00
if __name__ == "__main__":
2018-10-19 12:48:28 +00:00
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)
g.printGraph()
2019-10-05 05:14:13 +00:00
print("DFS:")
2018-10-19 12:48:28 +00:00
g.DFS()
# OUTPUT:
# 0  ->  1 -> 2
# 1  ->  2
# 2  ->  0 -> 3
# 3  ->  3
# DFS:
2019-10-05 05:14:13 +00:00
#  0 1 2 3