-
-
Notifications
You must be signed in to change notification settings - Fork 47.2k
Fixes #12857 Use collections.deque
as queue
in graphs BFS shortest path - breadth_first_search_shortest_path_2.py
#12861
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
base: master
Are you sure you want to change the base?
Conversation
Why make the proposed change? |
Thank you for the quick review. Yes,
A sample run result of the above code:
|
from collections import deque def breadth_first_search(graph, start, target):
|
Thanks for the input. It should be a separate pull request to modify the algorithm logic. |
Why not https://docs.python.org/3/library/queue.html ? Why not a single file with three implementations -- the original implementation + queue + dequeue -- with a |
Thanks for sharing the doc. The The
|
from collections import deque
def bfs_shortest_path_distance(graph: dict, start, target) -> int:
"""
Returns the shortest path distance from 'start' to 'target' in an unweighted graph.
Uses deque for efficient queue operations and includes visited set + distance map.
"""
if start == target:
return 0
queue = deque([start]) # FIX: Wrap start in a list
visited = set([start]) # Prevent revisiting nodes
dist = {start: 0} # Track distance of each node
while queue:
node = queue.popleft()
for neighbor in graph.get(node, []):
if neighbor not in visited:
visited.add(neighbor)
dist[neighbor] = dist[node] + 1
if neighbor == target:
return dist[neighbor]
queue.append(neighbor)
return -1 # Target not reachable
# Example usage / testing
if __name__ == "__main__":
graph = {
'A': ['B', 'C'],
'B': ['D'],
'C': [],
'D': []
}
print("Distance A -> D:", bfs_shortest_path_distance(graph, 'A', 'D')) # Output: 2
print("Distance A -> A:", bfs_shortest_path_distance(graph, 'A', 'A')) # Output: 0
print("Distance A -> Z:", bfs_shortest_path_distance(graph, 'A', 'Z')) # Output: -1 |
Describe your change:
Use
collections.deque
asqueue
in graphs BFS shortest path -breadth_first_search_shortest_path_2.py
Checklist: