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
1 | 0 | 1 |
1 | 0 | 1 |
1 | 1 | 0 |
then the output will be
1 | 0 | 1 |
1 | 0 | 1 |
2 | 1 | 0 |
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
- if matrix[y, x] is non-zero, then
- for x in range 0 to n, do
- 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
- if y is non-zero, then
- for x in range 0 to n, do
- 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
- if y + 1 < m, then
- for x in range n - 1 to 0, decrease by 1, do
- return matrix
Let us see the following implementation to get better understanding −
Example
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]]