# Program to count number of square submatrices with all ones using Python

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

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

So, if the input is like.

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

then the output will be 15, as there are 10 squares of side 1. 4 squares of side 2 and 1 square of side 3. Then total number of squares = 10 + 4 + 1 = 15.

To solve this, we will follow these steps −

• if matrix has single one, then

• return 1

• rows := row count of matrix

• cols := column count of matrix

• result := 0

• for row in range 0 to rows - 1, do

• for col in range 0 to cols - 1, do

• if row is same as 0 or col is same as 0, then

• if matrix[row, col] is same as 1, then

• result := result + 1

• otherwise when matrix[row, col] is same as 1, then

• square := 1 + (minimum of matrix[row-1,col], matrix[row,col-1] and matrix[row-1,col-1])

• matrix[row, col] := square

• result := result + square

• return result

Let us see the following implementation to get better understanding −

## Example

Live Demo

def solve(matrix):
if matrix == []:
return 1
rows = len(matrix)
cols = len(matrix)
result = 0
for row in range(rows):
for col in range(cols):
if (row == 0 or col == 0):
if matrix[row][col] == 1:
result += 1
elif matrix[row][col] == 1:
square = min(matrix[row-1][col], min(matrix[row][col-1], matrix[row-1][col-1])) + 1
matrix[row][col] = square
result += square
return result
matrix = [[0,1,1,1],[1,1,1,1],[0,1,1,1]]
print(solve(matrix))

## Input

{{0,1,1,1},{1,1,1,1},{0,1,1,1}}

## Output

15