Program to generate matrix where each cell holds Manhattan distance from nearest 0 in Python

The Manhattan distance between two points is the sum of absolute differences of their coordinates. In this problem, we need to find the Manhattan distance from each cell to the nearest 0 in a binary matrix.

Given a binary matrix, we transform it so each cell contains the Manhattan distance to the closest 0. At least one 0 is guaranteed to exist.

Example Input and Output

If the input matrix is ?

1 0 1
1 0 1
1 1 0

The output will be ?

1 0 1
1 0 1
2 1 0

The bottom-left cell has distance 2 because the nearest 0 is 2 Manhattan steps away.

Algorithm

We use a two-pass dynamic programming approach ?

  • Initialize all non-zero cells to infinity
  • First pass ? scan from top-left to bottom-right, updating distances from top and left neighbors
  • Second pass ? scan from bottom-right to top-left, updating distances from bottom and right neighbors

Implementation

import math

class Solution:
    def solve(self, matrix):
        m, n = len(matrix), len(matrix[0])
        
        # Step 1: Initialize non-zero cells to infinity
        for y in range(m):
            for x in range(n):
                if matrix[y][x]:
                    matrix[y][x] = math.inf
        
        # Step 2: First pass - top-left to bottom-right
        for y in range(m):
            for x in range(n):
                if y:
                    matrix[y][x] = min(matrix[y][x], matrix[y - 1][x] + 1)
                if x:
                    matrix[y][x] = min(matrix[y][x], matrix[y][x - 1] + 1)
        
        # Step 3: Second pass - bottom-right to top-left
        for y in range(m - 1, -1, -1):
            for x in range(n - 1, -1, -1):
                if y + 1 < m:
                    matrix[y][x] = min(matrix[y][x], matrix[y + 1][x] + 1)
                if x + 1 < n:
                    matrix[y][x] = min(matrix[y][x], matrix[y][x + 1] + 1)
        
        return matrix

# Test the solution
ob = Solution()
matrix = [[1, 0, 1], [1, 0, 1], [1, 1, 0]]
result = ob.solve(matrix)
print(result)

The output of the above code is ?

[[1, 0, 1], [1, 0, 1], [2, 1, 0]]

How It Works

The algorithm works in three phases ?

  1. Initialization ? Set all 1s to infinity, keep 0s as 0
  2. Forward pass ? Each cell checks if coming from top or left gives a shorter distance
  3. Backward pass ? Each cell checks if coming from bottom or right gives a shorter distance

After both passes, each cell contains the minimum Manhattan distance to any 0 in the matrix.

Time and Space Complexity

  • Time Complexity: O(m × n) where m and n are matrix dimensions
  • Space Complexity: O(1) as we modify the input matrix in-place

Conclusion

The two-pass dynamic programming approach efficiently computes Manhattan distances in O(m × n) time. The key insight is that optimal distances can be found by checking all four directions across two passes.

Updated on: 2026-03-25T12:39:08+05:30

281 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements