
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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
0 | 1 | 1 |
0 | 1 | 1 |
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
- if i is 0 or j is 0, then
- if mat[i, j] is 1, then
- for j in range 0 to column count of mat, do
- 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
- Related Articles
- Program to count number of square submatrices with all ones using Python
- Program to find number of square submatrices with 1 in python
- Program to count number of square submatix of 1s in the given matrix in C++
- Program to count number of islands in a given matrix in Python
- Program to count number of operations to convert binary matrix to zero matrix in C++
- Count Square Submatrices with All Ones in C++
- Program to count submatrices with all ones using Python
- Program to count number of surrounded islands in the matrix in python
- Program to find area of largest square of 1s in a given matrix in python
- Program to find number of special positions in a binary matrix using Python
- Python Program to Count number of binary strings without consecutive 1’
- Program to count number of words we can generate from matrix of letters in Python
- Python program to count number of vowels using set in a given string
- Program to count number of unique paths that includes given edges in Python
- Write a program in Python to count the number of digits in a given number N

Advertisements