- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# Program to count submatrices with all ones using Python

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

So, if the input is like

1 | 0 | 1 |

0 | 1 | 1 |

0 | 1 | 1 |

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

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

- Related Articles
- Program to count number of square submatrices with all ones using Python
- Count Square Submatrices with All Ones in C++
- Program to count number of square submatrices in given binary matrix in Python
- Program to find number of square submatrices with 1 in python
- Program to Find Out the Minimal Submatrices in Python
- Program to count substrings with all 1s in binary string in Python
- Program to replace all digits with characters using Python
- Count all prefixes in given string with greatest frequency using Python
- 8085 program to count the number of ones in contents of register B
- Program to count minimum semesters to cover all different courses in Python
- Program to count items matching a rule using Python
- Python program to count total set bits in all number from 1 to n.
- Program to count number of swaps required to group all 1s together in Python
- Program to check if binary string has at most one segment of ones or not using Python
- Program to count odd numbers in an interval range using Python