Program to find maximum value of k for which we can maintain safe distance in Python

PythonServer Side ProgrammingProgramming

Suppose we have a binary matrix. Here 0 signifies an empty cell, and a 1 signifies a cell with a person. The distance between two cells is the maximum value between the difference in x coordinates and the difference in y coordinates. Now matrix is considered safe with a factor k if there is an empty square such that the distance from the cell to each person in the matrix, and each side of the matrix is all greater or equal to k. We have to find the maximum value of factor k for which we can be safe.

So, if the input is like

00000
01010
01110
01110
00000

then the output will be 1, as in the middle cell the distance from the cell to each person in the grid is at least 1.

To solve this, we will follow these steps −

  • N := size of A

  • M := size of A[0]

  • for i in range 0 to N, do

    • for j in range 0 to M, do

      • A[i, j] := A[i, j] XOR 1

  • ans := 0

  • for i in range 0 to N, do

    • for j in range 0 to M, do

      • if i and j are non-zero and A[i, j] is 1, then

        • A[i, j] := 1 + minimum of A[i - 1, j], A[i, j - 1] and A[i - 1, j - 1]

        • ans = maximum of A[i, j] and ans

  • return (ans + 1) / 2

Example 

Let us see the following implementation to get better understanding −

 Live Demo

class Solution:
def solve(self, A):
   N = len(A)
   M = len(A[0])
   for i in range(N):
      for j in range(M):
         A[i][j] ^= 1
   ans = 0
   for i in range(N):
      for j in range(M):
         if i and j and A[i][j]:
            A[i][j] = 1 + min(A[i - 1][j], A[i][j - 1], A[i - 1][j - 1])
            ans = max(A[i][j], ans)
   return (ans + 1) // 2
ob = Solution()
matrix = [
   [0, 0, 0, 0, 0],
   [0, 1, 1, 1, 0],
   [0, 1, 0, 1, 0],
   [0, 1, 1, 1, 0],
   [0, 0, 0, 0, 0],
]
print(ob.solve(matrix))

Input

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

Output

1
raja
Published on 23-Dec-2020 06:12:36
Advertisements