Update queue implementation (#5388) · zinating/algorithms-python@e6cf13c · GitHub
Skip to content

Commit e6cf13c

Browse files
Crowtonpoyea
andauthored
Update queue implementation (TheAlgorithms#5388)
* Update queue implementation Popping the first element of a list takes O(n) time. Using a cyclic queue takes O(1) time. * Add queue changes from extra files * Update indentation * Add empty line between imports * Fix lines * Apply suggestions from code review Co-authored-by: John Law <johnlaw.po@gmail.com> Co-authored-by: John Law <johnlaw.po@gmail.com>
1 parent 3a4cc7e commit e6cf13c

3 files changed

Lines changed: 22 additions & 14 deletions

File tree

graphs/breadth_first_search.py

Lines changed: 7 additions & 5 deletions

graphs/breadth_first_search_2.py

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@
1414
"""
1515
from __future__ import annotations
1616

17+
from queue import Queue
18+
1719
G = {
1820
"A": ["B", "C"],
1921
"B": ["A", "D", "E"],
@@ -30,13 +32,14 @@ def breadth_first_search(graph: dict, start: str) -> set[str]:
3032
'ABCDEF'
3133
"""
3234
explored = {start}
33-
queue = [start]
34-
while queue:
35-
v = queue.pop(0) # queue.popleft()
35+
queue = Queue()
36+
queue.put(start)
37+
while not queue.empty():
38+
v = queue.get()
3639
for w in graph[v]:
3740
if w not in explored:
3841
explored.add(w)
39-
queue.append(w)
42+
queue.put(w)
4043
return explored
4144

4245

graphs/check_bipartite_graph_bfs.py

Lines changed: 8 additions & 5 deletions

0 commit comments

Comments
 (0)