-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathalgorithm.py
More file actions
27 lines (22 loc) · 794 Bytes
/
Copy pathalgorithm.py
File metadata and controls
27 lines (22 loc) · 794 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
from collections import deque
def bfs(graph):
"""
Perform a breadth-first search (BFS) traversal of a graph.
Parameters:
graph (dict): A dictionary where the keys are vertices and the values are sets of adjacent vertices.
Returns:
set: A set of all visited vertices in the graph.
Notes:
This function can handle disconnected graphs, graphs with a single node, and regular graphs.
"""
visited = set()
queue = deque()
for vertex in graph:
if vertex not in visited:
queue.append(vertex)
while queue:
vertex = queue.popleft()
if vertex not in visited:
visited.add(vertex)
queue.extend(graph[vertex] - visited)
return visited