Program to find area of largest square of 1s in a given matrix in python

PythonServer Side ProgrammingProgramming

Suppose we have a binary matrix, we have to find largest square of 1s in that given matrix.

So, if the input is like

1
0
0
0
0
1
1
0
0
0
0
0
1
1
0
1
1
1
1
0
0
0
1
1
1
1
0
0
0
1
1
1
1
0
0
0
1
1
1
1
0
0

then the output will be 16.

To solve this, we will follow these steps −

  • res := 0
  • for i in range 0 to size of matrix, do
    • res := maximum of res and matrix[i, 0]
  • for i in range 0 to size of matrix[0], do
    • res := maximum of res and matrix[0, i]
  • for i in range 1 to row count of matrix, do
    • for j in range 1 to column count of matrix, do
      • if matrix[i, j] is same as 1, then
        • matrix[i, j] = minimum of (matrix[i - 1, j], matrix[i - 1, j - 1] and matrix[i, j - 1]) + 1
      • res = maximum of res and matrix[i, j]
  • return res^2

Let us see the following implementation to get better understanding −

Example 

Live Demo

class Solution:
   def solve(self, matrix):
      res = 0
      for i in range(len(matrix)):
         res = max(res, matrix[i][0])
      for i in range(len(matrix[0])):
         res = max(res, matrix[0][i])

      for i in range(1, len(matrix)):
         for j in range(1, len(matrix[0])):
            if matrix[i][j] == 1:
               matrix[i][j] = min(matrix[i - 1][j], matrix[i - 1][j - 1], matrix[i][j - 1]) + 1

               res = max(res, matrix[i][j])

      return res * res

ob = Solution()
matrix = [
   [1, 0, 0, 0, 0, 1, 1],
   [0, 0, 0, 0, 0, 1, 1],
   [0, 1, 1, 1, 1, 0, 0],
   [0, 1, 1, 1, 1, 0, 0],
   [0, 1, 1, 1, 1, 0, 0],
   [0, 1, 1, 1, 1, 0, 0]
]
print(ob.solve(matrix))

Input

matrix = [  
[1, 0, 0, 0, 0, 1, 1],  
[0, 0, 0, 0, 0, 1, 1],  
[0, 1, 1, 1, 1, 0, 0],  
[0, 1, 1, 1, 1, 0, 0],  
[0, 1, 1, 1, 1, 0, 0],  
[0, 1, 1, 1, 1, 0, 0] ]

Output

16
raja
Published on 02-Dec-2020 05:37:53
Advertisements