Skip to content

Commit 098a9cf

Browse files
akashgkrishnanstokhos
authored andcommitted
Changed how the Visited nodes are tracked (TheAlgorithms#3811)
Updated the code to track visited Nodes with Set data structure instead of Lists to bring down the lookup time in visited from O(N) to O(1) as doing O(N) lookup each time in the visited List will become significantly slow when the graph grows
1 parent a230f1b commit 098a9cf

File tree

1 file changed

+4
-12
lines changed

1 file changed

+4
-12
lines changed

graphs/bfs_shortest_path.py

+4-12
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,6 @@
11
"""Breadth-first search shortest path implementations.
2-
32
doctest:
43
python -m doctest -v bfs_shortest_path.py
5-
64
Manual test:
75
python bfs_shortest_path.py
86
"""
@@ -19,22 +17,19 @@
1917

2018
def bfs_shortest_path(graph: dict, start, goal) -> str:
2119
"""Find shortest path between `start` and `goal` nodes.
22-
2320
Args:
2421
graph (dict): node/list of neighboring nodes key/value pairs.
2522
start: start node.
2623
goal: target node.
27-
2824
Returns:
2925
Shortest path between `start` and `goal` nodes as a string of nodes.
3026
'Not found' string if no path found.
31-
3227
Example:
3328
>>> bfs_shortest_path(graph, "G", "D")
3429
['G', 'C', 'A', 'B', 'D']
3530
"""
3631
# keep track of explored nodes
37-
explored = []
32+
explored = set()
3833
# keep track of all the paths to be checked
3934
queue = [[start]]
4035

@@ -61,24 +56,21 @@ def bfs_shortest_path(graph: dict, start, goal) -> str:
6156
return new_path
6257

6358
# mark node as explored
64-
explored.append(node)
59+
explored.add(node)
6560

6661
# in case there's no path between the 2 nodes
6762
return "So sorry, but a connecting path doesn't exist :("
6863

6964

7065
def bfs_shortest_path_distance(graph: dict, start, target) -> int:
7166
"""Find shortest path distance between `start` and `target` nodes.
72-
7367
Args:
7468
graph: node/list of neighboring nodes key/value pairs.
7569
start: node to start search from.
7670
target: node to search for.
77-
7871
Returns:
7972
Number of edges in shortest path between `start` and `target` nodes.
8073
-1 if no path exists.
81-
8274
Example:
8375
>>> bfs_shortest_path_distance(graph, "G", "D")
8476
4
@@ -92,7 +84,7 @@ def bfs_shortest_path_distance(graph: dict, start, target) -> int:
9284
if start == target:
9385
return 0
9486
queue = [start]
95-
visited = [start]
87+
visited = set(start)
9688
# Keep tab on distances from `start` node.
9789
dist = {start: 0, target: -1}
9890
while queue:
@@ -103,7 +95,7 @@ def bfs_shortest_path_distance(graph: dict, start, target) -> int:
10395
)
10496
for adjacent in graph[node]:
10597
if adjacent not in visited:
106-
visited.append(adjacent)
98+
visited.add(adjacent)
10799
queue.append(adjacent)
108100
dist[adjacent] = dist[node] + 1
109101
return dist[target]

0 commit comments

Comments
 (0)