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


Suppose we have a binary matrix. We have to find the same matrix, but each cell's value will be the Manhattan distance to the nearest 0. We can assume at least one 0 exists in the matrix.

So, if the input is like

101
101
110

then the output will be

101
101
210

as only the bottom left cell has distance of 2 to the nearest 0.

To solve this, we will follow these steps −

  • m := row size of matrix, n := column size of matrix
  • for y in range 0 to m, do
    • for x in range 0 to n, do
      • if matrix[y, x] is non-zero, then
        • matrix[y, x] := infinity
  • for y in range 0 to m, do
    • for x in range 0 to n, do
      • if y is non-zero, then
        • matrix[y, x] = minimum of matrix[y, x] and matrix[y - 1, x] + 1
      • if x is non-zero, then
        • matrix[y, x] = minimum of matrix[y, x] and matrix[y, x - 1] + 1
  • for y in range m - 1 to 0, decrease by 1, do
    • for x in range n - 1 to 0, decrease by 1, do
      • if y + 1 < m, then
        • matrix[y, x] = minimum of matrix[y, x] and matrix[y + 1, x] + 1
      • if x + 1 < n, then
        • matrix[y, x] = minimum of matrix[y, x] and matrix[y, x + 1] + 1
  • return matrix

Let us see the following implementation to get better understanding −

Example

 Live Demo

import math
class Solution:
   def solve(self, matrix):
      m, n = len(matrix), len(matrix[0])
      for y in range(m):
         for x in range(n):
            if matrix[y][x]:
               matrix[y][x] = math.inf
      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)
      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
ob = Solution()
matrix = [ [1, 0, 1], [1, 0, 1], [1, 1, 0] ]
print(ob.solve(matrix))

Input

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

Output

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

Updated on: 20-Nov-2020

165 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements