-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbfs.py
More file actions
28 lines (26 loc) · 727 Bytes
/
Copy pathbfs.py
File metadata and controls
28 lines (26 loc) · 727 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
from collections import deque
def bfs(graph, start):
"""
Breadth-First Search traversal from start node.
graph: dict of node→list of neighbors.
Returns list of visited nodes.
"""
visited, queue = set(), deque([start])
order = []
visited.add(start)
while queue:
node = queue.popleft()
order.append(node)
for nbr in graph.get(node, []):
if nbr not in visited:
visited.add(nbr)
queue.append(nbr)
return order
if __name__ == "__main__":
sample_graph = {
'A': ['B', 'C'],
'B': ['D', 'E'],
'C': ['F'],
'D': [], 'E': ['F'], 'F': []
}
print("BFS order:", bfs(sample_graph, 'A'))