Program to find number of square submatrices with 1 in python

PythonServer Side ProgrammingProgramming

Suppose we have a 2D binary matrix, we have to find the total number of square submatrices with all 1 s are there.

So, if the input is like

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

then the output will be 17 as there are 12 (1 x 1) squares, 4 (2 x 2) squares and 1 (3 x 3) square.

To solve this, we will follow these steps −

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

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)):
         for j in range(len(matrix[0])):
            if i == 0 or j == 0:
               res += matrix[i][j]
            elif matrix[i][j] == 1:
               matrix[i][j] = min(matrix[i][j - 1], matrix[i - 1][j], matrix[i - 1][j - 1]) + 1
               res += matrix[i][j]
      return res

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

Input

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

Output

17
raja
Published on 02-Dec-2020 04:56:02
Advertisements