-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBFS
More file actions
42 lines (32 loc) · 932 Bytes
/
BFS
File metadata and controls
42 lines (32 loc) · 932 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
32
33
34
35
36
37
38
39
40
41
42
from collections import deque
class Graph:
# constructor
def __init__(self, edges, n):
self.adjList = [[] for _ in range(n)]
# Add edges to undirected graph
for (src, dest) in edges:
self.adjList[src].append(dest)
self.adjList[dest].append(src)
# Perform BFS recursively on the graph
def recursiveBFS(graph, q, discovered):
if not q:
return
# deque front node and print it
v = q.popleft()
print(v, end='')
# do for every egde
for u in graph.adjList[v]:
if not discovered[u]:
# mark it as discovered and enqueue ot
discovered[u] = True
q.append(u)
recursiveBFS(graph, q, discovered)
if __name__ == "__main__":
# List of graph edges for diagram
edges = [
(1, 2), (1, 3), (1, 4), (2, 5), (2, 6),
(3, 10), (3, 7), (4, 8), (4, 11)
]
n = 12
#build a graph
graph = Graph(edges, n)