Skip to content

Commit c92a520

Browse files
authored
Update breadth_first_search.py (TheAlgorithms#1869)
1 parent 7aaf79c commit c92a520

File tree

1 file changed

+24
-30
lines changed

1 file changed

+24
-30
lines changed

graphs/breadth_first_search.py

+24-30
Original file line numberDiff line numberDiff line change
@@ -5,42 +5,40 @@
55

66
class Graph:
77
def __init__(self):
8-
self.vertex = {}
8+
self.vertices = {}
99

10-
# for printing the Graph vertices
1110
def printGraph(self):
12-
for i in self.vertex.keys():
13-
print(i, " -> ", " -> ".join([str(j) for j in self.vertex[i]]))
11+
"""prints adjacency list representation of graaph"""
12+
for i in self.vertices.keys():
13+
print(i, " : ", " -> ".join([str(j) for j in self.vertices[i]]))
1414

15-
# for adding the edge between two vertices
1615
def addEdge(self, fromVertex, toVertex):
17-
# check if vertex is already present,
18-
if fromVertex in self.vertex.keys():
19-
self.vertex[fromVertex].append(toVertex)
16+
"""adding the edge between two vertices"""
17+
if fromVertex in self.vertices.keys():
18+
self.vertices[fromVertex].append(toVertex)
2019
else:
21-
# else make a new vertex
22-
self.vertex[fromVertex] = [toVertex]
20+
self.vertices[fromVertex] = [toVertex]
2321

2422
def BFS(self, startVertex):
25-
# Take a list for stoting already visited vertices
26-
visited = [False] * len(self.vertex)
23+
# initialize set for storing already visited vertices
24+
visited = set()
2725

28-
# create a list to store all the vertices for BFS
26+
# create a first in first out queue to store all the vertices for BFS
2927
queue = []
3028

3129
# mark the source node as visited and enqueue it
32-
visited[startVertex] = True
30+
visited.add(startVertex)
3331
queue.append(startVertex)
3432

3533
while queue:
36-
startVertex = queue.pop(0)
37-
print(startVertex, end=" ")
34+
vertex = queue.pop(0)
3835

39-
# mark all adjacent nodes as visited and print them
40-
for i in self.vertex[startVertex]:
41-
if visited[i] == False:
42-
queue.append(i)
43-
visited[i] = True
36+
# loop through all adjacent vertex and enqueue it if not yet visited
37+
for adjacent_vertex in self.vertices[vertex]:
38+
if adjacent_vertex not in visited:
39+
queue.append(adjacent_vertex)
40+
visited.add(adjacent_vertex)
41+
return visited
4442

4543

4644
if __name__ == "__main__":
@@ -53,13 +51,9 @@ def BFS(self, startVertex):
5351
g.addEdge(3, 3)
5452

5553
g.printGraph()
56-
print("BFS:")
57-
g.BFS(2)
54+
# 0 : 1 -> 2
55+
# 1 : 2
56+
# 2 : 0 -> 3
57+
# 3 : 3
5858

59-
# OUTPUT:
60-
# 0  ->  1 -> 2
61-
# 1  ->  2
62-
# 2  ->  0 -> 3
63-
# 3  ->  3
64-
# BFS:
65-
# 2 0 3 1
59+
assert sorted(g.BFS(2)) == [0, 1, 2, 3]

0 commit comments

Comments
 (0)