0-1 Matrix
Problem Link: 01-matrix
Problem Statement
Given an m x n binary matrix mat, return a matrix that represents the distance of the nearest 0 for each cell.
The distance between two adjacent cells is defined as 1.
Examples
Example 1:
Input:
mat = [[0,0,0],
[0,1,0],
[1,1,1]]
Output:
[[0,0,0],
[0,1,0],
[1,2,1]]
Constraints
-
1 <= m, n <= 10^4 -
1 <= m * n <= 10^4 -
mat[i][j]is either0or1 -
There is at least one
0inmat
Intuition
This is a classic multi-source shortest path problem.
Key idea:
-
Each
0acts as a source with distance 0. -
Every
1should compute the shortest distance to the nearest 0. -
To solve this optimally, we initiate a BFS from all 0s at once.
The BFS ensures that we always reach any 1 from its nearest 0 first.
Approach: Multi-Source BFS
Step-by-Step Plan:
-
Initialize:
-
A result matrix
distwith all values as-1. -
A boolean matrix
visitedto track visited cells. -
A queue for BFS.
-
-
Preprocessing:
-
Push all cells with value
0into the queue with distance 0. -
Mark them visited.
-
-
Run BFS:
-
For each popped cell
(x, y):-
For all 4 directions (up, down, left, right), calculate neighbor
(nx, ny) -
If it is inside bounds and not visited:
-
Set
dist[nx][ny] = dist[x][y] + 1 -
Mark as visited
-
Push into queue
-
-
-
-
Return the final
distmatrix.
Java Code
class Solution {
public int[][] updateMatrix(int[][] mat) {
int m = mat.length;
int n = mat[0].length;
int[][] dist = new int[m][n];
boolean[][] visited = new boolean[m][n];
Queue<int[]> q = new LinkedList<>();
// Add all 0s to the queue
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (mat[i][j] == 0) {
q.offer(new int[]{i, j});
visited[i][j] = true;
}
}
}
// 4 directions
int[][] dirs = {{1,0},{-1,0},{0,1},{0,-1}};
while (!q.isEmpty()) {
int[] cell = q.poll();
int x = cell[0], y = cell[1];
for (int[] dir : dirs) {
int nx = x + dir[0];
int ny = y + dir[1];
if (nx >= 0 && ny >= 0 && nx < m && ny < n && !visited[nx][ny]) {
dist[nx][ny] = dist[x][y] + 1;
visited[nx][ny] = true;
q.offer(new int[]{nx, ny});
}
}
}
return dist;
}
}
Dry Run
Input:
[[0,0,0],
[0,1,0],
[1,1,1]]
Initial queue:
(0,0), (0,1), (0,2), (1,0), (1,2)
Initial dist:
[[0,0,0],
[0,-1,0],
[-1,-1,-1]]
Steps:
-
(1,1) gets value
1from any neighbor 0 -
(2,0), (2,2) get value
1 -
(2,1) gets value
2
Final output:
[[0,0,0],
[0,1,0],
[1,2,1]]
Time and Space Complexity
-
Time Complexity: O(m × n)
Each cell is processed at most once. -
Space Complexity: O(m × n)
Used by the queue, distance matrix, and visited matrix.
Applications
-
Real-time shortest path grid computations
-
Game development: distance from enemy, spawn, or safe zones
-
Matrix proximity problems in image processing
-
BFS template for multi-source propagation scenarios