The Wayback Machine - https://web.archive.org/web/20201126010943/https://github.com/TheAlgorithms/Python/pull/3811/files
Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Changed how the Visited nodes are tracked #3811

Merged
merged 1 commit into from Nov 21, 2020
Merged
Changes from all commits
Commits
File filter...
Filter file types
Jump to…
Jump to file
Failed to load files.
@@ -1,8 +1,6 @@
"""Breadth-first search shortest path implementations.
doctest:
python -m doctest -v bfs_shortest_path.py
Manual test:
python bfs_shortest_path.py
"""
@@ -19,22 +17,19 @@

def bfs_shortest_path(graph: dict, start, goal) -> str:
"""Find shortest path between `start` and `goal` nodes.
Args:
graph (dict): node/list of neighboring nodes key/value pairs.
start: start node.
goal: target node.
Returns:
Shortest path between `start` and `goal` nodes as a string of nodes.
'Not found' string if no path found.
Example:
>>> bfs_shortest_path(graph, "G", "D")
['G', 'C', 'A', 'B', 'D']
"""
# keep track of explored nodes
explored = []
explored = set()
# keep track of all the paths to be checked
queue = [[start]]

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

# mark node as explored
explored.append(node)
explored.add(node)

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


def bfs_shortest_path_distance(graph: dict, start, target) -> int:
"""Find shortest path distance between `start` and `target` nodes.
Args:
graph: node/list of neighboring nodes key/value pairs.
start: node to start search from.
target: node to search for.
Returns:
Number of edges in shortest path between `start` and `target` nodes.
-1 if no path exists.
Example:
>>> bfs_shortest_path_distance(graph, "G", "D")
4
@@ -92,7 +84,7 @@ def bfs_shortest_path_distance(graph: dict, start, target) -> int:
if start == target:
return 0
queue = [start]
visited = [start]
visited = set(start)
# Keep tab on distances from `start` node.
dist = {start: 0, target: -1}
while queue:
@@ -103,7 +95,7 @@ def bfs_shortest_path_distance(graph: dict, start, target) -> int:
)
for adjacent in graph[node]:
if adjacent not in visited:
visited.append(adjacent)
visited.add(adjacent)
queue.append(adjacent)
dist[adjacent] = dist[node] + 1
return dist[target]
ProTip! Use n and p to navigate between commits in a pull request.
You can’t perform that action at this time.