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
.
Input: mat =
[
[0,0,0],
[0,1,0],
[0,0,0]
]
Output:
[
[0,0,0],
[0,1,0],
[0,0,0]
]
Input: mat =
[
[0,0,0],
[0,1,0],
[1,1,1]
]
Output:
[
[0,0,0],
[0,1,0],
[1,2,1]
]
m == mat.length
n == mat[i].length
1 <= m, n <= 10^4
1 <= m * n <= 10^4
mat[i][j]
is either 0
or 1
.0
in mat
.1
.0
or 1
.To solve this problem efficiently, given the constraints, we can employ a Breadth-First Search (BFS) approach:
0
s in the matrix as starting points, as the distance to themselves is 0
.1
should have their distances set to a value indicating infinity (Integer.MAX_VALUE
), as they will be updated with the minimum distance during the BFS traversal.This approach ensures that all cells are processed in the shortest path manner due to the BFS traversal properties.
import java.util.*;
public class Solution {
public int[][] updateMatrix(int[][] mat) {
int rows = mat.length;
int cols = mat[0].length;
int[][] distances = new int[rows][cols];
Queue<int[]> queue = new LinkedList<>();
// Initialize distances and queue
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (mat[i][j] == 0) {
distances[i][j] = 0;
queue.offer(new int[]{i, j});
} else {
distances[i][j] = Integer.MAX_VALUE;
}
}
}
// Directions array for movement (down, up, right, left)
int[][] directions = \ use example from above
// BFS Traversal
while (!queue.isEmpty()) {
int[] cell = queue.poll();
int row = cell[0];
int col = cell[1];
for (int[] direction : directions) {
int newRow = row + direction[0];
int newCol = col + direction[1];
if (newRow >= 0 && newRow < rows && newCol >= 0 && newCol < cols) {
if (distances[newRow][newCol] > distances[row][col] + 1) {
distances[newRow][newCol] = distances[row][col] + 1;
queue.offer(new int[]{newRow, newCol});
}
}
}
}
return distances;
}
}
O(m * n)
— Each cell is processed in constant time, i.e., added and processed in the queue at most once.O(m * n)
— Using a queue to store cell positions and a distance matrix holding distances for each cell.This method efficiently processes the matrix and computes the required distances utilizing the BFS traversal technique.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?