You are given an m x n binary matrix grid where each cell contains either a 0 or a 1.
Write a function that returns a matrix of the same dimensions where each cell contains the distance to the nearest 0 in the original matrix. The distance between two adjacent cells is 1. If there is no 0 in the grid, return -1 for each cell.
Example 1
mat = [ [1, 0, 1], [0, 1, 0], [1, 1, 1],]
Output:
[ [1, 0, 1], [0, 1, 0], [1, 2, 1],]
Explanation
Since this question involves finding the shortest distance between each cell and the nearest 0, this is a good candidate for a breadth-first search (BFS) traversal.
The key idea here is to first enqueue all cells with value 0 into the queue. This allows us to gradually find the distance of each cell to the nearest 0 using a BFS traversal.
Let’s look at example input grid to help visualize the process:
[ [1, 0, 1], [0, 1, 0], [1, 1, 1],]
Step 1: Initialize the Queue
We’ll start by initializing the output grid with all cells set to -1 to indicate that the distance to the nearest 0 is unknown. We’ll use BFS to gradually update the distance of each cell in the output grid.
Next, we can initialize the BFS queue with the positions of all cells that have a value of 0. We can also update the distances of these cells in the output grid to 0 directly (doing so also serves the purpose of marking these cells as visited).
# the coordinates of cells with value 0queue = [ (0, 1), (1, 0), (1, 2) ]
# setting the distances of cells with value 0 to 0 in the output gridoutput = [ [-1, 0, -1], [0, -1, 0], [-1, -1, -1],]
Step 2: Perform BFS Traversal (Distance 1)
Next, we’ll start the BFS traversal with all the cells with value 0. All the neighbors of the cells currently in the BFS queue that currently have a value of -1 are at distance 1 from the nearest 0. We’ll update the distances of these neighbors in the output grid to 1, and enqueue them into the BFS queue.
Now, all the neighbors of the cells currently in the BFS queue that have a value of -1 are at distance of 2 from the nearest 0. We’ll update the distances of these neighbors in the output grid to 2, and enqueue them into the BFS queue.
queue = [ (2, 1) ]
output = [ [1, 0, 1], [0, 1, 0], [1, 2, 1],]
Step 4: Perform BFS Traversal (Distance 3)
At this step, all the neighbors of the cells in the BFS queue have been visited already, so we don’t need to enqueue any more cells.
queue = []
Step 5: Return the Output Grid
Since the queue is now empty, we can terminate the BFS traversal and return the output grid, which contains the distances of each cell to the nearest 0.
[ [1, 0, 1], [0, 1, 0], [1, 2, 1],]
Solution
from collections import dequeclass Solution: def updateMatrix(self, mat): rows, cols = len(mat), len(mat[0]) output = [[-1] * cols for _ in range(rows)] queue = deque() # Step 1: Initialize the queue with all the 0 cells # set their distance to 0 in the output grid for r in range(rows): for c in range(cols): if mat[r][c] == 0: queue.append((r, c)) output[r][c] = 0 directions = [(0, 1), (1, 0), (0, -1), (-1, 0)] # Step 2: Perform BFS traversal distance = 1 while queue: for _ in range(len(queue)): r, c = queue.popleft() for dr, dc in directions: nr, nc = r + dr, c + dc if 0 <= nr < rows and 0 <= nc < cols: if output[nr][nc] == -1: output[nr][nc] = distance queue.append((nr, nc)) distance += 1 # Step 5: Return the output grid return output
class Solution { public int[][] updateMatrix(int[][] mat) { int rows = mat.length; int cols = mat[0].length; int[][] output = new int[rows][cols]; Queue<int[]> queue = new LinkedList<>(); // Step 1: Initialize the queue with all the 0 cells // set their distance to 0 in the output grid for (int r = 0; r < rows; r++) { for (int c = 0; c < cols; c++) { if (mat[r][c] == 0) { queue.offer(new int[]{r, c}); output[r][c] = 0; } else { output[r][c] = -1; } } } int[][] directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; // Step 2: Perform BFS traversal int distance = 1; while (!queue.isEmpty()) { int levelSize = queue.size(); for (int i = 0; i < levelSize; i++) { int[] cell = queue.poll(); int r = cell[0], c = cell[1]; for (int[] dir : directions) { int nr = r + dir[0]; int nc = c + dir[1]; if (nr >= 0 && nr < rows && nc >= 0 && nc < cols) { if (output[nr][nc] == -1) { output[nr][nc] = distance; queue.offer(new int[]{nr, nc}); } } } } distance++; } // Step 5: Return the output grid return output; }}
type Cell struct { Row, Col int}func updateMatrix(mat [][]int) [][]int { rows := len(mat) cols := len(mat[0]) output := make([][]int, rows) for i := range output { output[i] = make([]int, cols) for j := range output[i] { output[i][j] = -1 } } var queue []Cell // Step 1: Initialize the queue with all the 0 cells // set their distance to 0 in the output grid for r := 0; r < rows; r++ { for c := 0; c < cols; c++ { if mat[r][c] == 0 { queue = append(queue, Cell{r, c}) output[r][c] = 0 } } } directions := []Cell{{0, 1}, {1, 0}, {0, -1}, {-1, 0}} // Step 2: Perform BFS traversal distance := 1 for len(queue) > 0 { levelSize := len(queue) for i := 0; i < levelSize; i++ { cell := queue[0] queue = queue[1:] r, c := cell.Row, cell.Col for _, dir := range directions { nr := r + dir.Row nc := c + dir.Col if nr >= 0 && nr < rows && nc >= 0 && nc < cols { if output[nr][nc] == -1 { output[nr][nc] = distance queue = append(queue, Cell{nr, nc}) } } } } distance++ } // Step 5: Return the output grid return output}
class Solution { updateMatrix(mat: number[][]): number[][] { const rows = mat.length; const cols = mat[0].length; const output: number[][] = Array(rows).fill(0).map(() => Array(cols).fill(-1)); const queue: [number, number][] = []; // Step 1: Initialize the queue with all the 0 cells // set their distance to 0 in the output grid for (let r = 0; r < rows; r++) { for (let c = 0; c < cols; c++) { if (mat[r][c] === 0) { queue.push([r, c]); output[r][c] = 0; } } } const directions: [number, number][] = [[0, 1], [1, 0], [0, -1], [-1, 0]]; // Step 2: Perform BFS traversal let distance = 1; while (queue.length > 0) { const levelSize = queue.length; for (let i = 0; i < levelSize; i++) { const [r, c] = queue.shift()!; for (const [dr, dc] of directions) { const nr = r + dr; const nc = c + dc; if (nr >= 0 && nr < rows && nc >= 0 && nc < cols) { if (output[nr][nc] === -1) { output[nr][nc] = distance; queue.push([nr, nc]); } } } } distance++; } // Step 5: Return the output grid return output; }}