Breadth-first search (BFS) explores a graph in waves: first the start vertex, then every vertex one edge away, then every vertex two edges away, and so on. A plain FIFO queue is all it needs. Because vertices come out of the queue in order of their distance, BFS finds shortest paths in unweighted graphs in O(V + E) time, which makes it the go-to tool for "minimum number of moves" problems on graphs, grids and puzzle states.
Think of it like
Ripples in a pond
Drop a stone into still water. The ripple reaches every point 1 cm away before any point 2 cm away, and every point 2 cm away before any point 3 cm away. BFS is that ripple: each ring of the wave is one level of the search, and the moment the ripple first touches a point is exactly its shortest distance from where the stone landed.
How it works
BFS keeps a queue of vertices that have been discovered but not yet processed. It repeatedly takes the oldest one, looks at its neighbors, and appends every neighbor it has not seen before. Since the queue is first-in, first-out, everything at distance d leaves the queue before anything at distance d + 1.
- 1
Seed the queue
Set
dist[s] = 0, marksas visited and enqueue it. Every other vertex starts undiscovered. - 2
Dequeue the oldest vertex
Pop
ufrom the front of the queue. Its distance is already final. - 3
Discover its neighbors
For each neighbor
vofuthat is not yet visited: mark it visited, setdist[v] = dist[u] + 1andparent[v] = u, and enqueue it. - 4
Repeat until the queue is empty
Every vertex reachable from
sis dequeued exactly once. Unreached vertices keep distance infinity (or -1).
from collections import deque
dist = {source: 0} # doubles as the visited set
queue = deque([source])
while queue:
u = queue.popleft() # FIFO: oldest discovered vertex first
for v in adj[u]:
if v not in dist: # first discovery is the shortest one
dist[v] = dist[u] + 1
queue.append(v)Worked example
Run BFS from A on the undirected graph with edges A-B, A-C, B-D, C-D, C-E, D-F, E-F, scanning neighbors in alphabetical order. Watch how D is discovered from B and is not added again when C sees it.
| Step | Dequeue | Newly discovered (distance) | Queue after |
|---|---|---|---|
| Start | none | A (0) | [A] |
| 1 | A | B (1), C (1) | [B, C] |
| 2 | B | D (2) | [C, D] |
| 3 | C | E (2); D is already discovered | [D, E] |
| 4 | D | F (3) | [E, F] |
| 5 | E | none: C and F are already discovered | [F] |
| 6 | F | none | [] |
Shortest paths and path reconstruction
Distances alone rarely satisfy a problem; you usually need the route. Record parent[v] = u at the moment v is discovered. The parent pointers form a BFS tree (a shortest-path tree): following them from any vertex leads back to the source along a shortest path. Walk from the target to the source, then reverse.
def reconstruct_path(parent: list[int], source: int, target: int) -> list[int]:
if target != source and parent[target] == -1:
return [] # target never discovered: unreachable
path = [target]
while path[-1] != source:
path.append(parent[path[-1]]) # step back toward the source
return path[::-1] # source ... targetProcessing level by level
Some problems care about the level boundaries themselves: "how many minutes until...", "return the nodes at each depth", "minimum number of rounds". Snapshot the queue length at the start of each round and process exactly that many vertices. Everything appended during the round belongs to the next level.
level = 0
visited = {source}
queue = deque([source])
while queue:
for _ in range(len(queue)): # exactly the vertices at distance `level`
u = queue.popleft()
for v in adj[u]:
if v not in visited:
visited.add(v)
queue.append(v)
level += 1 # one full ring of the ripple is doneMulti-source BFS
When the question is "how far is every cell from the nearest source", do not run one BFS per source. Put all sources in the queue at distance 0 and run a single BFS. It behaves exactly like one BFS from an imaginary super-source connected to every real source by a zero-length edge, so it still costs O(V + E) no matter how many sources there are.
One BFS per source
kseparate searchesO(k · (V + E))time- Then take the minimum per vertex
- Times out when
kis large (every gate, every rotten orange)
Multi-source BFS
- All
ksources enqueued at distance 0 O(V + E)time- Each vertex labeled with its distance to the nearest source
- Same code as ordinary BFS, different initialization
Example: rotting oranges
In a grid, 2 is a rotten orange, 1 a fresh one and 0 empty. Each minute, rot spreads to the 4 neighbors of every rotten orange. Enqueue every rotten orange at time 0, then process one level per minute. The answer is the number of levels it takes to rot every fresh orange, or -1 if some fresh orange is never reached. The full solution is in the implementations below.
0-1 BFS
If every edge weight is either 0 or 1, you do not need Dijkstra's Algorithm's priority queue. Use a double-ended queue: when relaxing an edge of weight 0, push the neighbor to the front (same distance as the current vertex); for weight 1, push it to the back (one more). The deque always holds at most two distinct distances in sorted order, so it behaves like a priority queue with O(1) operations.
- Cost to change direction: in a grid where following the arrow in a cell is free and changing it costs 1, edges are 0 or 1 (Minimum Cost to Make at Least One Valid Path in a Grid).
- Breaking walls: moving into an empty cell costs 0 and moving into a wall you must remove costs 1.
- Reversing edges: keep each directed edge with weight 0 and add the reverse with weight 1 to find the minimum number of edges to reverse.
Bipartite check by 2-coloring
A graph is bipartite exactly when it has no odd cycle. BFS tests this directly: color the start vertex 0 and every newly discovered neighbor the opposite color of its discoverer. If an edge ever connects two vertices of the same color, the two BFS paths to them plus that edge form an odd cycle. Restart from every uncolored vertex so disconnected graphs are fully checked.
from collections import deque
def is_bipartite(adj: list[list[int]]) -> bool:
color = [-1] * len(adj) # -1 = uncolored
for start in range(len(adj)): # the graph may be disconnected
if color[start] != -1:
continue
color[start] = 0
queue = deque([start])
while queue:
u = queue.popleft()
for v in adj[u]:
if color[v] == -1:
color[v] = 1 - color[u] # put v on the other side
queue.append(v)
elif color[v] == color[u]:
return False # same side: odd cycle found
return TrueBFS on grids and state spaces
Most BFS interview questions are grids or puzzles where the graph is implicit (see Graph Fundamentals). Each cell or state is a vertex, legal moves are edges, and you generate neighbors on the fly.
- Use direction arrays (
(1,0), (-1,0), (0,1), (0,-1)) and check bounds before indexing the grid. - Mark visited in a boolean matrix, or overwrite the cell in place (
grid[r][c] = 2) if mutation is allowed. - Flatten
(r, c)tor * cols + cwhen you need integer ids or a compact visited array. - When the problem adds a resource (walls you may break, keys you hold), the vertex becomes
(r, c, resource)and the state space multiplies. - For a single source and single target in a huge state space, bidirectional BFS (searching from both ends until the frontiers meet) explores roughly
2 · b^(d/2)states instead ofb^d.
BFS vs DFS
| Property | BFS | DFS |
|---|---|---|
| Frontier structure | Queue (FIFO) | Stack or recursion (LIFO) |
| Shortest path in unweighted graphs | Yes | No |
| Extra memory | O(width of the widest level) | O(depth of the search) |
| Discovery and finish times | No | Yes: the basis of cycle detection, SCCs, bridges |
| Typical uses | Minimum moves, levels, nearest source, bipartite check | Components, cycles, topological sort, backtracking |
Complexity
Each vertex is enqueued and dequeued at most once: O(V). When a vertex is dequeued its adjacency list is scanned once, and by the handshake lemma the lists have E entries in total (directed) or 2E (undirected): O(E). Total O(V + E). With an adjacency matrix, scanning a row costs O(V) per vertex, so BFS becomes O(V²).
Complexity
| Variant | Time | Space | Notes |
|---|---|---|---|
| BFS, adjacency list | O(V + E) | O(V) | Each vertex and edge processed once |
| BFS, adjacency matrix | O(V²) | O(V) | Scanning a row costs O(V) |
| Grid BFS (R × C cells) | O(R · C) | O(R · C) | At most 4 neighbors per cell |
| Multi-source BFS | O(V + E) | O(V) | Independent of the number of sources |
| 0-1 BFS | O(V + E) | O(V) | Deque replaces the priority queue |
| Bipartite check | O(V + E) | O(V) | One BFS per component |
Space counts the queue plus visited/dist/parent arrays, not the graph itself.
Implementation
Single-source BFS that records `dist` and `parent`, then rebuilds a fewest-edges path. The example graph is the worked example (A to F as 0 to 5).
from collections import deque
def bfs(adj: list[list[int]], source: int) -> tuple[list[int], list[int]]:
n = len(adj)
dist = [-1] * n # -1 means "not discovered yet"
parent = [-1] * n
dist[source] = 0
queue = deque([source])
while queue:
u = queue.popleft()
for v in adj[u]:
if dist[v] == -1: # mark when ENQUEUED so v enters the queue once
dist[v] = dist[u] + 1
parent[v] = u
queue.append(v)
return dist, parent
def reconstruct_path(parent: list[int], source: int, target: int) -> list[int]:
if target != source and parent[target] == -1:
return [] # unreachable
path = [target]
while path[-1] != source:
path.append(parent[path[-1]])
return path[::-1]
adj = [[1, 2], [0, 3], [0, 3, 4], [1, 2, 5], [2, 5], [3, 4]]
dist, parent = bfs(adj, 0)
print(dist) # [0, 1, 1, 2, 2, 3]
print(reconstruct_path(parent, 0, 5)) # [0, 1, 3, 5]Key takeaways
- BFS explores in rings of increasing distance using a FIFO queue, and runs in
O(V + E). - In an unweighted graph, the first time BFS discovers a vertex is along a shortest path; keep
parentpointers to rebuild it. - Mark vertices visited when you enqueue them so each enters the queue exactly once.
- Multi-source BFS seeds the queue with every source and computes nearest-source distances in one pass.
- With 0/1 edge weights, a deque (0-1 BFS) replaces Dijkstra's heap; for general weights use Dijkstra's Algorithm.
Common pitfalls
- Marking visited on dequeue, which lets the same vertex be enqueued many times and blows up time and memory.
- Using BFS on a weighted graph and expecting the cheapest path; BFS minimizes edge count, not total weight.
- Using
list.pop(0)in Python orarray.shift()in JavaScript as the dequeue, turningO(V + E)intoO(V²). - Forgetting to restart from every unvisited vertex when the graph is disconnected (components, bipartite check).
- Checking grid bounds after indexing the grid, or forgetting that blocked start or target cells need special handling.
Interview tips
- Say why BFS gives shortest paths (non-decreasing distance order) before coding; interviewers often ask.
- For grid problems, write the direction array and bounds check once and reuse them; it removes a whole class of bugs.
- If several starting points exist, reach for multi-source BFS immediately instead of looping BFS per source.
- When the state includes extra information (keys collected, obstacles removed), say so explicitly and include it in the visited key.
Real-world applications
- Fewest hops in computer networks and social networks (degrees of separation).
- Web crawlers exploring pages in order of link distance from seed URLs.
- Garbage collectors (Cheney's copying collector traverses live objects breadth-first).
- Puzzle solving and game AI: minimum moves in mazes, Rubik's cube subproblems, sliding puzzles.
- Flood-style spreading simulations: fire, infection, signal propagation on grids.
- Finding augmenting paths in the Edmonds-Karp max-flow algorithm.
Practice problems
Test yourself
Why do we mark a vertex as visited when it is enqueued rather than when it is dequeued?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.