Sub topic 3
BFS on Grids and Implicit Graphs
This chapter assumes you already know the core BFS loop, why it marks vertices visited when they are enqueued, and how it computes shortest distances in unweighted graphs. Here we apply that loop to several common problem shapes.
Grids as Implicit Graphs
An implicit graph is one where neighbors are computed on demand instead of stored. In a grid, each open cell is a vertex, and its neighbors are the four adjacent open cells. A distance array can also serve as the visited marker.
from collections import deque
def grid_distances(grid, start):
rows, cols = len(grid), len(grid[0])
dist = [[-1] * cols for _ in range(rows)]
r0, c0 = start
dist[r0][c0] = 0
queue = deque([start])
while queue:
r, c = queue.popleft()
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
nr, nc = r + dr, c + dc
if (0 <= nr < rows and 0 <= nc < cols
and grid[nr][nc] == '.' and dist[nr][nc] == -1):
dist[nr][nc] = dist[r][c] + 1
queue.append((nr, nc))
return dist
grid = ['..#',
'.#.',
'...']
print(grid_distances(grid, (0, 0))) # [[0, 1, -1], [1, -1, 5], [2, 3, 4]]A common error is checking bounds after indexing, which raises IndexError or, with negative indices, silently wraps around in Python.
Connected Components and Bipartiteness
To find all connected components, loop over every vertex and start a new BFS from each one that is still unvisited. Each new start is one component.
A graph is bipartite if its vertices split into two groups with every edge crossing between them. Run the component loop and color each layer opposite to the one before it. If any edge joins two vertices of the same color, the graph is not bipartite. A triangle fails this test and a square passes.
Variants
- Multi-source BFS: Put every source in the queue at distance 0 before the loop starts. The result is each vertex's distance to its nearest source, computed in one pass.
- 0-1 BFS: When edge weights are only 0 or 1, use a deque. A neighbor reached by a 0-weight edge goes to the front, and one reached by a 1-weight edge goes to the back. This gives correct distances in O(V + E) time without a priority queue. Vertices can be relaxed more than once, so compare distances instead of checking a visited set.
- Bidirectional BFS: Search from the start and the goal at the same time and stop when the two frontiers meet. With branching factor b and distance d, each side explores about b^(d/2) vertices instead of b^d.
Choosing Between BFS and DFS
| Need | Prefer |
|---|---|
| Fewest-edge path | BFS |
| Layer-by-layer processing | BFS |
| Cycle detection, topological order | DFS |
| Low memory on wide, shallow graphs | DFS |
| Components or reachability only | Either |
Exercise
A grid contains several fires. Each minute, fire spreads to adjacent open cells. How do you compute the minute at which each cell catches fire in one traversal?
Show answer
Use multi-source BFS. Enqueue every fire cell at distance 0, then run the grid BFS. Each cell's distance is the minute it ignites.