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
32
33
34
35
36
37
38
39
40
41
| from collections import deque
class Graph:
def __init__(self):
self.adj_list = {}
def add_vertex(self, vertex):
self.adj_list.setdefault(vertex, [])
def add_edge(self, v1, v2):
if v1 in self.adj_list and v2 in self.adj_list:
self.adj_list[v1].append(v2)
self.adj_list[v2].append(v1)
def bfs_find(self, start_vertex, target_vertex):
if start_vertex not in self.adj_list:
return False
visited = set()
queue = deque([start_vertex])
while queue:
vertex = queue.popleft()
if vertex == target_vertex:
return True # Target vertex found
if vertex not in visited:
visited.add(vertex)
# Enqueue all unvisited neighbors
queue.extend(neighbor for neighbor in self.adj_list[vertex] if neighbor not in visited)
return False # Target vertex not found
graph = Graph()
for vertex in ['A', 'B', 'C', 'D', 'E']:
graph.add_vertex(vertex)
edges = [('A', 'B'), ('A', 'C'), ('B', 'D'), ('C', 'D'), ('C', 'E'), ('D', 'E')]
for v1, v2 in edges:
graph.add_edge(v1, v2)
print(graph.bfs_find('A', 'E')) # Output : True
|