Why This Matters
Many graph questions are disguised as grids. Each cell is a vertex, and valid moves to neighboring cells are edges. Matrix traversal is the bridge between arrays, graphs, and DP tables.
The invariant is cell validity: every queued or recursive cell must be inside bounds, unvisited if required, and satisfy the problem's value condition.
Prerequisite Check
Review Arrays, BFS, and DFS. You should be able to map (row, col) to neighboring cells.
Learning Objectives
By the end, you should be able to:
- Generate valid four-direction and eight-direction neighbors.
- Treat a grid as an implicit graph.
- Count connected components with flood fill.
- Choose BFS for shortest grid paths and DFS for region exploration.
- Avoid boundary and mutation bugs.
Core Idea
Represent each cell by (row, col). Generate candidate moves, filter invalid cells, and maintain visited state.
| Pattern | Invariant | Typical problem |
|---|---|---|
| Flood fill | visited cells belong to the current region | islands, image fill |
| Grid BFS | queue cells have finalized step distance | shortest maze path |
| Spiral traversal | boundaries shrink after each side | spiral order |
| DP table traversal | dependencies already computed | grid path counts |
Visual Model
cell (r,c) neighbors:
(r-1,c)
(r,c-1) (r,c) (r,c+1)
(r+1,c)
The graph is implicit: you do not need to build adjacency lists for every cell.
Non-Example or Failure Mode
Recursive DFS on a huge grid can exceed the Python recursion limit. For production-size grids, use an explicit stack or queue.
Another failure mode is marking visited after recursion. Mark before expanding so cycles through neighboring cells cannot revisit the same cell.
Worked Example
Count islands in:
1 1 0
0 1 0
1 0 1
Start at the first unvisited 1, flood fill the top-left component, then continue scanning. The grid has three islands under four-direction connectivity.
LeetCode-Style Problem Patterns
| Pattern | Recognition signal | Move |
|---|---|---|
| Number of islands | connected 1 cells | DFS/BFS flood fill |
| Shortest path in binary matrix | minimum moves in grid | BFS by distance levels |
| Rotting oranges | simultaneous spread | multi-source BFS |
| Spiral matrix | visit boundary layers | shrink top/right/bottom/left |
Common Mistakes
| Mistake | Correction |
|---|---|
| Swapping rows and columns. | Name rows and cols; bounds are different. |
| Forgetting visited state. | Mutate a copy or use a set. |
| Using DFS for shortest path. | Use BFS when all moves have equal cost. |
| Assuming diagonal adjacency. | Check whether the problem says four or eight directions. |
Diagnostic Questions
| Question type | Question | Answer signal |
|---|---|---|
| Definition | How is a grid a graph? | Cells are vertices and valid moves are edges. |
| Example / non-example | Does four-direction island counting connect diagonals? | No, unless the problem defines diagonal moves. |
| Computation | What is flood-fill complexity for an m x n grid? | O(mn) time and up to O(mn) visited/stack/queue space. |
| Proof | Why does marking visited before expansion matter? | It prevents neighboring cells from re-adding the same cell. |
| Transfer | When does grid traversal become DP? | When each cell depends on previously computed neighbor states rather than arbitrary graph reachability. |
Exercises
Beginner:
- List valid neighbors for the corner and center of a
3 x 3grid. - Count islands by hand under four-direction connectivity.
- Explain why a grid can be an implicit graph.
Intermediate:
- Implement shortest path in a binary matrix with BFS.
- Write spiral-order traversal using shrinking boundaries.
Challenge:
- Compare DFS flood fill and union-find for dynamic island-counting variants.
Diagram Recommendation
Type: grid-neighbor overlay.
Caption: "Each cell connects to valid neighboring cells under the chosen movement rule."
Purpose: Prevent row/column and diagonal-connectivity mistakes.
Implementation Task
Implement island counting using an explicit stack. Keep the input grid unmodified by storing visited coordinates separately.
Run matrix traversal island count
This cell counts four-direction islands and checks boundary behavior.
Output will appear here.
Next Topics
References
- MIT OpenCourseWare. 6.006 Introduction to Algorithms, Spring 2020: https://ocw.mit.edu/courses/6-006-introduction-to-algorithms-spring-2020/
- Princeton Algorithms, Graph Processing: https://algs4.cs.princeton.edu/40graphs/
- Python documentation, sequence types: https://docs.python.org/3/library/stdtypes.html#sequence-types-list-tuple-range