bfs

🏠

Super simple BFS.

 1class 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
16g = {}
17g[1] = [2, 6]
18g[2] = [7, 3, 1]
19g[3] = [4, 2]
20g[4] = [5, 7, 3]
21g[5] = [4, 7, 6]
22g[6] = [5, 1]
23g[7] = [5, 4, 2]
24
25g1 = Graph()
26g1.adjlist = g
27g1.bfs(1)

Pasted image 21.png

Output:

11
22
36
47
53
65
74

See also:

depth first search