GRAPHS · 10 MIN
Breadth-First Search
BFS explores a graph level by level using a queue; it finds shortest paths in unweighted graphs.
BYTE explains
- Start from a source, mark it visited, push it into a queue.
- Pop a node, visit all unvisited neighbours, enqueue them.
- Time O(V + E).
Real world: News spreading: first your friends hear it, then their friends, and so on.
Watch it move
Visit node 0 (level 0)
1/6
Code
from collections import deque
def bfs(g, s):
seen, q, order = {s}, deque([s]), []
while q:
u = q.popleft(); order.append(u)
for v in g[u]:
if v not in seen:
seen.add(v); q.append(v)
return orderTry it in the online compiler →Checkpoint quiz
Which structure does BFS use?