Skip to content

Commit 15ae8c4

Browse files
committed
fix: bfs enhancement with collections.deque
1 parent 7a0fee4 commit 15ae8c4

File tree

1 file changed

+6
-4
lines changed

1 file changed

+6
-4
lines changed

graphs/breadth_first_search_shortest_path_2.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,8 @@
1515
"G": ["C"],
1616
}
1717

18+
from collections import deque
19+
1820

1921
def bfs_shortest_path(graph: dict, start, goal) -> list[str]:
2022
"""Find shortest path between `start` and `goal` nodes.
@@ -36,7 +38,7 @@ def bfs_shortest_path(graph: dict, start, goal) -> list[str]:
3638
# keep track of explored nodes
3739
explored = set()
3840
# keep track of all the paths to be checked
39-
queue = [[start]]
41+
queue = deque([[start]])
4042

4143
# return path if start is goal
4244
if start == goal:
@@ -45,7 +47,7 @@ def bfs_shortest_path(graph: dict, start, goal) -> list[str]:
4547
# keeps looping until all possible paths have been checked
4648
while queue:
4749
# pop the first path from the queue
48-
path = queue.pop(0)
50+
path = queue.popleft()
4951
# get the last node from the path
5052
node = path[-1]
5153
if node not in explored:
@@ -88,12 +90,12 @@ def bfs_shortest_path_distance(graph: dict, start, target) -> int:
8890
return -1
8991
if start == target:
9092
return 0
91-
queue = [start]
93+
queue = deque([start])
9294
visited = set(start)
9395
# Keep tab on distances from `start` node.
9496
dist = {start: 0, target: -1}
9597
while queue:
96-
node = queue.pop(0)
98+
node = queue.popleft()
9799
if node == target:
98100
dist[target] = (
99101
dist[node] if dist[target] == -1 else min(dist[target], dist[node])

0 commit comments

Comments
 (0)