Skip to content

Commit 18444bf

Browse files
committedJun 27, 2017
Breadth First Search Graph Traversal
1 parent 1d3e869 commit 18444bf

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed
 

‎Graph/P01_BreadthFirstSearch.py

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
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 BFS(self, startVertex):
22+
# Take a list for stoting already visited vertexes
23+
visited = [False] * len(self.vertex)
24+
25+
# create a list to store all the vertexes for BFS
26+
queue = []
27+
28+
# mark the source node as visited and enqueue it
29+
visited[startVertex] = True
30+
queue.append(startVertex)
31+
32+
while queue:
33+
startVertex = queue.pop(0)
34+
print(startVertex, end = ' ')
35+
36+
# mark all adjacent nodes as visited and print them
37+
for i in self.vertex[startVertex]:
38+
if visited[i] == False:
39+
queue.append(i)
40+
visited[i] = True
41+
42+
if __name__ == '__main__':
43+
g = Graph()
44+
g.addEdge(0, 1)
45+
g.addEdge(0, 2)
46+
g.addEdge(1, 2)
47+
g.addEdge(2, 0)
48+
g.addEdge(2, 3)
49+
g.addEdge(3, 3)
50+
51+
g.printGraph()
52+
print('BFS:')
53+
g.BFS(2)
54+
55+
# OUTPUT:
56+
# 0  ->  1 -> 2
57+
# 1  ->  2
58+
# 2  ->  0 -> 3
59+
# 3  ->  3
60+
# BFS:
61+
# 2 0 3 1

0 commit comments

Comments
 (0)