The 01 Matrix interview question asks you to take a binary matrix (consisting of 0s and 1s) and calculate the distance of the nearest 0 for each cell. If a cell contains a 0, the distance is naturally 0. If it contains a 1, you must find the shortest path (moving up, down, left, or right) to any cell containing a 0.
Companies like Google, Meta, and Amazon favor this problem because it tests your ability to handle multi-source shortest path problems. While a single-source search is common, the 01 Matrix coding problem requires you to efficiently process multiple starting points simultaneously, demonstrating a deep understanding of graph traversal efficiency.
The most efficient approach follows the Breadth-First Search (BFS) interview pattern. Specifically, it uses a Multi-Source BFS. Instead of starting a BFS from every '1' (which would be too slow), you start by adding all '0's to a queue and "radiating" outward. Alternatively, it can be solved using Dynamic Programming by performing two passes (top-left to bottom-right and vice versa) to propagate minimum distances.
Imagine a 3x3 grid:
1 1 1
1 1 1
0 1 1
The only 0 is at the bottom-left .
Whenever you see a grid problem asking for the "shortest distance" to a specific set of targets, think Multi-Source BFS first. It’s almost always more performant than repetitive DFS or standard DP.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Minimum Moves to Spread Stones Over Grid | Medium | Solve | |
| As Far from Land as Possible | Medium | Solve | |
| Disconnect Path in a Binary Matrix by at Most One Flip | Medium | Solve | |
| Minimum Path Sum | Medium | Solve | |
| Snakes and Ladders | Medium | Solve |