Program to count number of square submatrices in given binary matrix in Python


Suppose we have a 2D binary matrix. We have to find the total number of square submatrices present in matrix, where all elements are 1.

So, if the input is like

011
011

then the output will be 5, because there is one (2 × 2) square, and four (1 × 1) squares

To solve this, we will follow these steps −

  • if mat is empty, then
    • return 0
  • c := 0
  • for i in range 0 to row count of mat, do
    • for j in range 0 to column count of mat, do
      • if mat[i, j] is 1, then
        • if i is 0 or j is 0, then
          • c := c + 1
        • otherwise,
          • temp = (minimum of (mat[i-1, j-1], mat[i, j-1] and mat[i-1, j]) + mat[i, j]
          • c := c + temp
          • mat[i, j] := temp
  • return c

Example

Let us see the following implementation to get better understanding −

def solve(mat):
   if mat == []:
      return 0
   c = 0

   for i in range(len(mat)):
      for j in range(len(mat[0])):
         if mat[i][j] == 1:
            if i == 0 or j == 0:
               c += 1
            else:
               temp = (min(mat[i - 1][j - 1], mat[i][j - 1], mat[i - 1][j]) + mat[i][j])
               c += temp
               mat[i][j] = temp
   return c

matrix = [
   [0, 1, 1],
   [0, 1, 1]
]
print(solve(matrix))

Input

[[2, 6],[3, 4],[4, 7],[5, 5]]

Output

5

Updated on: 18-Oct-2021

330 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements