-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLab 7.py
More file actions
31 lines (25 loc) · 687 Bytes
/
Lab 7.py
File metadata and controls
31 lines (25 loc) · 687 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
29
30
31
from collections import deque
def bfs(graph, start):
visited = set()
queue = deque([start])
visited.add(start)
while queue:
vertex = queue.popleft()
print(vertex, end=" ")
for neighbor in graph[vertex]:
if neighbor not in visited:
queue.append(neighbor)
visited.add(neighbor)
# Example graph represented as an adjacency list
graph = {
'A': ['B', 'C'],
'B': ['A', 'D', 'E'],
'C': ['A', 'F'],
'D': ['B'],
'E': ['B', 'F'],
'F': ['C', 'E']
}
# Starting vertex for BFS
start_vertex = 'A'
print("Breadth First Search starting from vertex", start_vertex)
bfs(graph, start_vertex)