In this problem, we are given an m x n binary matrix filled with 0s and 1s. We need to return the distance of the nearest 0 for each cell. The distance between two adjacent cells is 1, and we can only move in four directions: up, down, left, right.
Dynamic Programming Solution
The key insight for solving this problem with dynamic programming is that the distance of a cell to the nearest 0 depends on its neighbors' distances. If we process the matrix in the correct order, we can build up our solution efficiently.
python
def updateMatrix(mat):
rows, cols = len(mat), len(mat)
MAX_VALUE = rows * cols # Value larger than any possible distance
# Initialize distance matrix
dp = [[0 if mat[i][j] == 0 else MAX_VALUE for j in range(cols)] for i in range(rows)]
# First pass: top-left to bottom-right
for i in range(rows):
for j in range(cols):
if mat[i][j] == 1:
# Consider left and top neighbors
left = dp[i][j-1] if j > 0 else MAX_VALUE
top = dp[i-1][j] if i > 0 else MAX_VALUE
dp[i][j] = min(left, top) + 1
# Second pass: bottom-right to top-left
for i in range(rows-1, -1, -1):
for j in range(cols-1, -1, -1):
if mat[i][j] == 1:
# Consider right and bottom neighbors
right = dp[i][j+1] if j < cols-1 else MAX_VALUE
bottom = dp[i+1][j] if i < rows-1 else MAX_VALUE
dp[i][j] = min(dp[i][j], min(right, bottom) + 1)
return dp
This solution works in two passes:
First pass considers distances from the top and left (propagating from top-left to bottom-right)
Second pass considers distances from the bottom and right (propagating from bottom-right to top-left)
By combining these two passes, we ensure we've considered all possible paths to find the shortest distance.
Verifying Correctness
Let's verify that our dynamic programming approach is correct:
Base Case: Cells containing 0 have distance 0, which is correctly initialized in our solution.
Recursive Relation: For a cell with value 1, its distance to the nearest 0 is:
This relation holds because to reach the nearest 0 from position (i,j), we must go through one of its four neighbors and then follow the shortest path from that neighbor to a 0.
Comprehensive Consideration: By performing two passes in opposite directions, we ensure that we've considered all possible paths to reach a 0 from any cell.
Optimal Substructure: The problem exhibits optimal substructure, a requirement for dynamic programming. The solution to the overall problem can be constructed from solutions to its subproblems.
We can visualize this with an example:
code
[1, 1, 0]
[1, 1, 1]
[0, 1, 1]
After our two-pass algorithm, the result is:
code
[2, 1, 0]
[1, 2, 1]
[0, 1, 2]
Which correctly shows the distance of each cell to the nearest 0.
Optimization: BFS Approach
The dynamic programming solution has time complexity O(m×n) and requires two passes. A breadth-first search approach can solve this in a single pass with the same time complexity:
python
from collections import deque
def updateMatrix(mat):
rows, cols = len(mat), len(mat)
dist = [[float('inf')] * cols for _ in range(rows)]
queue = deque()
# Add all 0s to the queue
for i in range(rows):
for j in range(cols):
if mat[i][j] == 0:
dist[i][j] = 0
queue.append((i, j))
directions = [(1, 0), (-1, 0), (0, 1), (0, -1)] # Four possible movements
# BFS from all 0 cells simultaneously
while queue:
i, j = queue.popleft()
for di, dj in directions:
ni, nj = i + di, j + dj
if 0 <= ni < rows and 0 <= nj < cols and dist[ni][nj] > dist[i][j] + 1:
dist[ni][nj] = dist[i][j] + 1
queue.append((ni, nj))
return dist
The BFS approach:
Starts from all cells containing 0 simultaneously
Processes cells in order of increasing distance from 0s
Guarantees the shortest path to each cell
Comparison of Approaches
Time Complexity: Both approaches have O(m×n) time complexity, as each cell is processed a constant number of times.
Space Complexity: Both require O(m×n) extra space for the distance matrix and, in the BFS case, the queue.
Advantages of DP:
More memory efficient in practice (doesn't need a queue)
Conceptually demonstrates the principle of building complex solutions from simpler ones
Advantages of BFS:
More intuitive for shortest path problems
Single pass through the matrix
More generalizable to weighted graphs or irregular connectivity
For this specific problem, the BFS approach might be slightly more efficient in practice, especially for large matrices, due to its single-pass nature.
Final Thoughts
Both approaches demonstrate the power of different algorithmic paradigms. The dynamic programming solution showcases how to break down the problem into optimal subproblems, while the BFS solution illustrates the natural fit of graph algorithms for distance-related problems.
When solving shortest path problems, it's valuable to consider both approaches, as the best choice may depend on the specific constraints and characteristics of the problem.