From 15ae8c44e3dd57455290f2502e2fc94aa8075f0f Mon Sep 17 00:00:00 2001 From: riokuma Date: Sun, 3 Aug 2025 14:46:41 +0900 Subject: [PATCH 1/2] fix: bfs enhancement with collections.deque --- graphs/breadth_first_search_shortest_path_2.py | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/graphs/breadth_first_search_shortest_path_2.py b/graphs/breadth_first_search_shortest_path_2.py index 4f9b6e65bdf3..b36c6f5ce1f0 100644 --- a/graphs/breadth_first_search_shortest_path_2.py +++ b/graphs/breadth_first_search_shortest_path_2.py @@ -15,6 +15,8 @@ "G": ["C"], } +from collections import deque + def bfs_shortest_path(graph: dict, start, goal) -> list[str]: """Find shortest path between `start` and `goal` nodes. @@ -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: @@ -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: @@ -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]) From b1b970b510af83ce4600d0ac502e3c2e9f8637da Mon Sep 17 00:00:00 2001 From: riokuma Date: Tue, 5 Aug 2025 07:48:20 +0900 Subject: [PATCH 2/2] fix: import location --- graphs/breadth_first_search_shortest_path_2.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/graphs/breadth_first_search_shortest_path_2.py b/graphs/breadth_first_search_shortest_path_2.py index b36c6f5ce1f0..6d9a9ae3fe19 100644 --- a/graphs/breadth_first_search_shortest_path_2.py +++ b/graphs/breadth_first_search_shortest_path_2.py @@ -5,6 +5,8 @@ python bfs_shortest_path.py """ +from collections import deque + demo_graph = { "A": ["B", "C", "E"], "B": ["A", "D", "E"], @@ -15,8 +17,6 @@ "G": ["C"], } -from collections import deque - def bfs_shortest_path(graph: dict, start, goal) -> list[str]: """Find shortest path between `start` and `goal` nodes.