1
1
"""Breadth-first search shortest path implementations.
2
-
3
2
doctest:
4
3
python -m doctest -v bfs_shortest_path.py
5
-
6
4
Manual test:
7
5
python bfs_shortest_path.py
8
6
"""
19
17
20
18
def bfs_shortest_path (graph : dict , start , goal ) -> str :
21
19
"""Find shortest path between `start` and `goal` nodes.
22
-
23
20
Args:
24
21
graph (dict): node/list of neighboring nodes key/value pairs.
25
22
start: start node.
26
23
goal: target node.
27
-
28
24
Returns:
29
25
Shortest path between `start` and `goal` nodes as a string of nodes.
30
26
'Not found' string if no path found.
31
-
32
27
Example:
33
28
>>> bfs_shortest_path(graph, "G", "D")
34
29
['G', 'C', 'A', 'B', 'D']
35
30
"""
36
31
# keep track of explored nodes
37
- explored = []
32
+ explored = set ()
38
33
# keep track of all the paths to be checked
39
34
queue = [[start ]]
40
35
@@ -61,24 +56,21 @@ def bfs_shortest_path(graph: dict, start, goal) -> str:
61
56
return new_path
62
57
63
58
# mark node as explored
64
- explored .append (node )
59
+ explored .add (node )
65
60
66
61
# in case there's no path between the 2 nodes
67
62
return "So sorry, but a connecting path doesn't exist :("
68
63
69
64
70
65
def bfs_shortest_path_distance (graph : dict , start , target ) -> int :
71
66
"""Find shortest path distance between `start` and `target` nodes.
72
-
73
67
Args:
74
68
graph: node/list of neighboring nodes key/value pairs.
75
69
start: node to start search from.
76
70
target: node to search for.
77
-
78
71
Returns:
79
72
Number of edges in shortest path between `start` and `target` nodes.
80
73
-1 if no path exists.
81
-
82
74
Example:
83
75
>>> bfs_shortest_path_distance(graph, "G", "D")
84
76
4
@@ -92,7 +84,7 @@ def bfs_shortest_path_distance(graph: dict, start, target) -> int:
92
84
if start == target :
93
85
return 0
94
86
queue = [start ]
95
- visited = [ start ]
87
+ visited = set ( start )
96
88
# Keep tab on distances from `start` node.
97
89
dist = {start : 0 , target : - 1 }
98
90
while queue :
@@ -103,7 +95,7 @@ def bfs_shortest_path_distance(graph: dict, start, target) -> int:
103
95
)
104
96
for adjacent in graph [node ]:
105
97
if adjacent not in visited :
106
- visited .append (adjacent )
98
+ visited .add (adjacent )
107
99
queue .append (adjacent )
108
100
dist [adjacent ] = dist [node ] + 1
109
101
return dist [target ]
0 commit comments