01 Matrix
Problem Statement
You get a grid made of 0s and 1s. For every cell, find the distance to the nearest 0. Two cells are one step apart when they share a side (up, down, left or right).
Return a grid of the same size. Each cell holds its distance to the nearest 0. A 0 is at distance 0 from itself.
mat, an m × n grid of 0s and 1s.
An m × n grid. Each cell holds the number of steps to its nearest 0.
The only 1 is in the centre. It touches a 0 on all four sides, so its distance is 1.
The bottom-middle 1 has no 0 next to it. Its nearest 0 is two steps away, through the centre 1.
The 0 is at the right end. Each 1 is one step further from it than the 1 to its right.
- • The grid has m rows and n columns, with 1 ≤ m, n ≤ 10^4 and 1 ≤ m · n ≤ 10^4.
- • Each cell is 0 or 1.
- • There is at least one 0 in the grid.
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
For each 1, run a BFS until the first 0 comes out of the queue
Put all the 0s in the queue at distance 0; one BFS gives every cell its distance
For each cell that holds a 1, run a BFS from that cell. The first 0 that comes out of the queue is its nearest 0, so the BFS depth at that point is the answer for that cell. A 0 gets 0. Each BFS starts from scratch, so the same cells are searched again and again.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Graph BFS / DFS translate into production architectures and low-level memory mechanics.