01 Matrix
542. 01 Matrix
Given an m x n
binary matrix mat
, return the distance of the nearest 0
for each cell.
The distance between two adjacent cells is 1
.
Initial Grid
0
0
0
0
1
0
1
1
1
→
Final Grid (Distances)
0
0
0
0
1
0
1
2
1
Solution Explained
The problem asks for the distance of the nearest 0 for each cell in a binary matrix. This is a classic shortest path problem on an unweighted graph, which is a perfect use case for Breadth-First Search (BFS).
The core idea is to start a multi-source BFS from all cells containing 0 simultaneously. We can think of the 0s as the starting points of our search.
Algorithm Steps (BFS)
- Initialize a distance matrix, marking 0s as distance 0 and others as unvisited (e.g., -1 or infinity).
- Create a queue and add the coordinates of all cells containing 0.
- While the queue is not empty, process cells level by level.
- For each cell, explore its four neighbors.
- If a neighbor is unvisited, update its distance and add it to the queue.
This process guarantees that we find the shortest path from a 0 to every other cell because BFS explores the grid layer by layer.
01 Matrix (BFS) Visualization
Progress1 / 1
Ready to start.
0
0
0
0
∞
0
∞
∞
∞
Queue
Code Example