1- """Breadth-first search shortest path implementations.
1+ """Breadth-first search the shortest path implementations.
22doctest:
3- python -m doctest -v bfs_shortest_path .py
3+ python -m doctest -v breadth_first_search_shortest_path_2 .py
44Manual test:
5- python bfs_shortest_path .py
5+ python breadth_first_search_shortest_path_2 .py
66"""
77
8+ from collections import deque
9+
810demo_graph = {
911 "A" : ["B" , "C" , "E" ],
1012 "B" : ["A" , "D" , "E" ],
1719
1820
1921def bfs_shortest_path (graph : dict , start , goal ) -> list [str ]:
20- """Find shortest path between `start` and `goal` nodes.
22+ """Find the shortest path between `start` and `goal` nodes.
2123 Args:
2224 graph (dict): node/list of neighboring nodes key/value pairs.
2325 start: start node.
@@ -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 :
@@ -68,13 +70,13 @@ def bfs_shortest_path(graph: dict, start, goal) -> list[str]:
6870
6971
7072def bfs_shortest_path_distance (graph : dict , start , target ) -> int :
71- """Find shortest path distance between `start` and `target` nodes.
73+ """Find the shortest path distance between `start` and `target` nodes.
7274 Args:
7375 graph: node/list of neighboring nodes key/value pairs.
7476 start: node to start search from.
7577 target: node to search for.
7678 Returns:
77- Number of edges in shortest path between `start` and `target` nodes.
79+ Number of edges in the shortest path between `start` and `target` nodes.
7880 -1 if no path exists.
7981 Example:
8082 >>> bfs_shortest_path_distance(demo_graph, "G", "D")
@@ -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