Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to count number of square submatrices in given binary matrix in Python
A square submatrix is a subset of elements from a matrix arranged in a square pattern. In a binary matrix, we want to count square submatrices where all elements are 1. This problem uses dynamic programming to efficiently count all possible squares.
Problem Understanding
Given a binary matrix, we need to find the total number of square submatrices containing only 1s. For example:
| 0 | 1 | 1 |
| 0 | 1 | 1 |
This matrix has 5 square submatrices: one (2×2) square and four (1×1) squares.
Algorithm Approach
We use dynamic programming where each cell stores the size of the largest square ending at that position:
- If matrix is empty, return 0
- Initialize counter c = 0
- For each cell (i, j):
- If mat[i][j] is 1:
- If it's on first row or column, it can only form 1×1 square
- Otherwise, calculate: min(top-left, top, left) + 1
- Add this value to counter and update the cell
- If mat[i][j] is 1:
- Return total count
Implementation
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))
5
How It Works
The algorithm transforms the matrix during computation:
def solve_with_steps(mat):
if not mat:
return 0
print("Original matrix:")
for row in mat:
print(row)
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]) + 1
c += temp
mat[i][j] = temp
print("\nAfter processing:")
for row in mat:
print(row)
print(f"\nTotal squares: {c}")
return c
matrix = [
[0, 1, 1],
[0, 1, 1]
]
solve_with_steps(matrix)
Original matrix: [0, 1, 1] [0, 1, 1] After processing: [0, 1, 1] [0, 1, 2] Total squares: 5
Example with Larger Matrix
def count_square_submatrices(matrix):
if not matrix:
return 0
count = 0
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if matrix[i][j] == 1:
if i == 0 or j == 0:
count += 1
else:
square_size = min(matrix[i-1][j-1], matrix[i][j-1], matrix[i-1][j]) + 1
count += square_size
matrix[i][j] = square_size
return count
# Test with different matrices
test_cases = [
[[1, 1, 1], [1, 1, 1], [1, 1, 1]],
[[0, 1, 1, 1], [1, 1, 1, 1], [0, 1, 1, 1]]
]
for i, matrix in enumerate(test_cases):
result = count_square_submatrices([row[:] for row in matrix]) # Copy to preserve original
print(f"Matrix {i+1}: {result} square submatrices")
Matrix 1: 14 square submatrices Matrix 2: 15 square submatrices
Conclusion
This dynamic programming solution efficiently counts square submatrices in O(m×n) time by storing the largest square size at each position. The key insight is that each cell's value represents how many squares end at that position.
