Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 6 additions & 4 deletions graphs/breadth_first_search_shortest_path_2.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
python bfs_shortest_path.py
"""

from collections import deque

demo_graph = {
"A": ["B", "C", "E"],
"B": ["A", "D", "E"],
Expand Down Expand Up @@ -36,7 +38,7 @@ def bfs_shortest_path(graph: dict, start, goal) -> list[str]:
# keep track of explored nodes
explored = set()
# keep track of all the paths to be checked
queue = [[start]]
queue = deque([[start]])

# return path if start is goal
if start == goal:
Expand All @@ -45,7 +47,7 @@ def bfs_shortest_path(graph: dict, start, goal) -> list[str]:
# keeps looping until all possible paths have been checked
while queue:
# pop the first path from the queue
path = queue.pop(0)
path = queue.popleft()
# get the last node from the path
node = path[-1]
if node not in explored:
Expand Down Expand Up @@ -88,12 +90,12 @@ def bfs_shortest_path_distance(graph: dict, start, target) -> int:
return -1
if start == target:
return 0
queue = [start]
queue = deque([start])
visited = set(start)
# Keep tab on distances from `start` node.
dist = {start: 0, target: -1}
while queue:
node = queue.pop(0)
node = queue.popleft()
if node == target:
dist[target] = (
dist[node] if dist[target] == -1 else min(dist[target], dist[node])
Expand Down