Python/graphs/breadth_first_search.py

60 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):
2020-04-19 13:56:52 +00:00
self.vertices = {}
2018-10-19 12:48:28 +00:00
def printGraph(self):
2020-04-19 13:56:52 +00:00
"""prints adjacency list representation of graaph"""
for i in self.vertices.keys():
print(i, " : ", " -> ".join([str(j) for j in self.vertices[i]]))
2018-10-19 12:48:28 +00:00
def addEdge(self, fromVertex, toVertex):
2020-04-19 13:56:52 +00:00
"""adding the edge between two vertices"""
if fromVertex in self.vertices.keys():
self.vertices[fromVertex].append(toVertex)
2018-10-19 12:48:28 +00:00
else:
2020-04-19 13:56:52 +00:00
self.vertices[fromVertex] = [toVertex]
2018-10-19 12:48:28 +00:00
def BFS(self, startVertex):
2020-04-19 13:56:52 +00:00
# initialize set for storing already visited vertices
visited = set()
2018-10-19 12:48:28 +00:00
2020-04-19 13:56:52 +00:00
# create a first in first out queue to store all the vertices for BFS
2018-10-19 12:48:28 +00:00
queue = []
# mark the source node as visited and enqueue it
2020-04-19 13:56:52 +00:00
visited.add(startVertex)
2018-10-19 12:48:28 +00:00
queue.append(startVertex)
while queue:
2020-04-19 13:56:52 +00:00
vertex = queue.pop(0)
2018-10-19 12:48:28 +00:00
2020-04-19 13:56:52 +00:00
# loop through all adjacent vertex and enqueue it if not yet visited
for adjacent_vertex in self.vertices[vertex]:
if adjacent_vertex not in visited:
queue.append(adjacent_vertex)
visited.add(adjacent_vertex)
return visited
2018-10-19 12:48:28 +00:00
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()
2020-04-19 13:56:52 +00:00
# 0 : 1 -> 2
# 1 : 2
# 2 : 0 -> 3
# 3 : 3
2018-10-19 12:48:28 +00:00
2020-04-19 13:56:52 +00:00
assert sorted(g.BFS(2)) == [0, 1, 2, 3]