1
- """Breadth-first search shortest path implementations.
1
+ """Breadth-first search the shortest path implementations.
2
2
doctest:
3
- python -m doctest -v bfs_shortest_path .py
3
+ python -m doctest -v breadth_first_search_shortest_path_2 .py
4
4
Manual test:
5
- python bfs_shortest_path .py
5
+ python breadth_first_search_shortest_path_2 .py
6
6
"""
7
7
8
+ from collections import deque
9
+
8
10
demo_graph = {
9
11
"A" : ["B" , "C" , "E" ],
10
12
"B" : ["A" , "D" , "E" ],
17
19
18
20
19
21
def 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.
21
23
Args:
22
24
graph (dict): node/list of neighboring nodes key/value pairs.
23
25
start: start node.
@@ -36,7 +38,7 @@ def bfs_shortest_path(graph: dict, start, goal) -> list[str]:
36
38
# keep track of explored nodes
37
39
explored = set ()
38
40
# keep track of all the paths to be checked
39
- queue = [[ start ]]
41
+ queue = deque ([ start ])
40
42
41
43
# return path if start is goal
42
44
if start == goal :
@@ -45,7 +47,7 @@ def bfs_shortest_path(graph: dict, start, goal) -> list[str]:
45
47
# keeps looping until all possible paths have been checked
46
48
while queue :
47
49
# pop the first path from the queue
48
- path = queue .pop ( 0 )
50
+ path = queue .popleft ( )
49
51
# get the last node from the path
50
52
node = path [- 1 ]
51
53
if node not in explored :
@@ -68,13 +70,13 @@ def bfs_shortest_path(graph: dict, start, goal) -> list[str]:
68
70
69
71
70
72
def 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.
72
74
Args:
73
75
graph: node/list of neighboring nodes key/value pairs.
74
76
start: node to start search from.
75
77
target: node to search for.
76
78
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.
78
80
-1 if no path exists.
79
81
Example:
80
82
>>> bfs_shortest_path_distance(demo_graph, "G", "D")
@@ -88,12 +90,12 @@ def bfs_shortest_path_distance(graph: dict, start, target) -> int:
88
90
return - 1
89
91
if start == target :
90
92
return 0
91
- queue = [ start ]
93
+ queue = deque ( start )
92
94
visited = set (start )
93
95
# Keep tab on distances from `start` node.
94
96
dist = {start : 0 , target : - 1 }
95
97
while queue :
96
- node = queue .pop ( 0 )
98
+ node = queue .popleft ( )
97
99
if node == target :
98
100
dist [target ] = (
99
101
dist [node ] if dist [target ] == - 1 else min (dist [target ], dist [node ])
0 commit comments