4
4
Manual test:
5
5
python bfs_shortest_path.py
6
6
"""
7
- graph = {
7
+ demo_graph = {
8
8
"A" : ["B" , "C" , "E" ],
9
9
"B" : ["A" , "D" , "E" ],
10
10
"C" : ["A" , "F" , "G" ],
15
15
}
16
16
17
17
18
- def bfs_shortest_path (graph : dict , start , goal ) -> str :
18
+ def bfs_shortest_path (graph : dict , start , goal ) -> list [ str ] :
19
19
"""Find shortest path between `start` and `goal` nodes.
20
20
Args:
21
21
graph (dict): node/list of neighboring nodes key/value pairs.
@@ -25,8 +25,12 @@ def bfs_shortest_path(graph: dict, start, goal) -> str:
25
25
Shortest path between `start` and `goal` nodes as a string of nodes.
26
26
'Not found' string if no path found.
27
27
Example:
28
- >>> bfs_shortest_path(graph , "G", "D")
28
+ >>> bfs_shortest_path(demo_graph , "G", "D")
29
29
['G', 'C', 'A', 'B', 'D']
30
+ >>> bfs_shortest_path(demo_graph, "G", "G")
31
+ ['G']
32
+ >>> bfs_shortest_path(demo_graph, "G", "Unknown")
33
+ []
30
34
"""
31
35
# keep track of explored nodes
32
36
explored = set ()
@@ -35,7 +39,7 @@ def bfs_shortest_path(graph: dict, start, goal) -> str:
35
39
36
40
# return path if start is goal
37
41
if start == goal :
38
- return "That was easy! Start = goal"
42
+ return [ start ]
39
43
40
44
# keeps looping until all possible paths have been checked
41
45
while queue :
@@ -59,7 +63,7 @@ def bfs_shortest_path(graph: dict, start, goal) -> str:
59
63
explored .add (node )
60
64
61
65
# in case there's no path between the 2 nodes
62
- return "So sorry, but a connecting path doesn't exist :("
66
+ return []
63
67
64
68
65
69
def bfs_shortest_path_distance (graph : dict , start , target ) -> int :
@@ -72,11 +76,11 @@ def bfs_shortest_path_distance(graph: dict, start, target) -> int:
72
76
Number of edges in shortest path between `start` and `target` nodes.
73
77
-1 if no path exists.
74
78
Example:
75
- >>> bfs_shortest_path_distance(graph , "G", "D")
79
+ >>> bfs_shortest_path_distance(demo_graph , "G", "D")
76
80
4
77
- >>> bfs_shortest_path_distance(graph , "A", "A")
81
+ >>> bfs_shortest_path_distance(demo_graph , "A", "A")
78
82
0
79
- >>> bfs_shortest_path_distance(graph , "A", "H ")
83
+ >>> bfs_shortest_path_distance(demo_graph , "A", "Unknown ")
80
84
-1
81
85
"""
82
86
if not graph or start not in graph or target not in graph :
@@ -102,5 +106,5 @@ def bfs_shortest_path_distance(graph: dict, start, target) -> int:
102
106
103
107
104
108
if __name__ == "__main__" :
105
- print (bfs_shortest_path (graph , "G" , "D" )) # returns ['G', 'C', 'A', 'B', 'D']
106
- print (bfs_shortest_path_distance (graph , "G" , "D" )) # returns 4
109
+ print (bfs_shortest_path (demo_graph , "G" , "D" )) # returns ['G', 'C', 'A', 'B', 'D']
110
+ print (bfs_shortest_path_distance (demo_graph , "G" , "D" )) # returns 4
0 commit comments