bfs

🏠

Super simple BFS.

 1 class Graph:
 2     def __init__(self):
 3         self.visited = set()
 4 
 5     def bfs(self, node):
 6         q = [node]
 7         while q:
 8             current = q.pop(0)
 9             if current in self.visited:
10                 continue
11             self.visited.add(current)
12             print(current)
13             q.extend(neigh for neigh in self.adjlist[current])
14 
15 
16 g = {}
17 g[1] = [2, 6]
18 g[2] = [7, 3, 1]
19 g[3] = [4, 2]
20 g[4] = [5, 7, 3]
21 g[5] = [4, 7, 6]
22 g[6] = [5, 1]
23 g[7] = [5, 4, 2]
24 
25 g1 = Graph()
26 g1.adjlist = g
27 g1.bfs(1)

Pasted image 21.png

Output:

1 1
2 2
3 6
4 7
5 3
6 5
7 4

See also:

dfs