Program to count submatrices with all ones using Python

PythonServer Side ProgrammingProgramming

Suppose we have m x n binary matrix, we have to find how many submatrices have all ones.

So, if the input is like

101
011
011

then the output will be 13 as there are 6 (1x1) matrices, 3 (2,1) matrices, 2 (1x2) matrices, 1 (3x1) matrix and 1 (4x4) matrix.

To solve this, we will follow these steps −

  • m := row count of matrix

  • n := column count of matrix

  • dp := a zero matrix of same size m x n

  • for i in range 0 to m - 1, do

    • for j in range 0 to n - 1, do

      • if i is same as 0 and matrix[i, j], then

        • dp[i, j] := 1

      • otherwise when matrix[i][j] is non-zero, then

        • dp[i, j] := dp[i-1, j] + 1

  • total := 0

  • for i in range 0 to m - 1, do

    • for j in range 0 to n - 1, do

      • for k in range j+1 to n, do

        • total := total + minimum of dp[i,j] to dp[i,k]

  • return total

Let us see the following implementation to get better understanding −

Example

 Live Demo

def solve(matrix):
   m = len(matrix)
   n = len(matrix[0])
   dp = [[0] * n for _ in range(m)]
   for i in range(m):
      for j in range(n):
         if i == 0 and matrix[i][j]:
            dp[i][j] = 1
         elif matrix[i][j]:
            dp[i][j] = dp[i-1][j] + 1
   total = 0
   for i in range(m):
      for j in range(n):
         for k in range(j+1, n+1):
            total += min(dp[i][j:k])
   return total
matrix = [[1,0,1],[0,1,1],[0,1,1]]
print(solve(matrix))

Input

[4,6,7,8], 11

Output

13
raja
Published on 28-May-2021 12:26:15
Advertisements