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 find number of square submatrices with 1 in python
Suppose we have a 2D binary matrix, we have to find the total number of square submatrices with all 1s. This problem can be solved using dynamic programming by tracking the largest square ending at each position.
So, if the input is like:
Then the output will be 17 as there are 12 (1×1) squares, 4 (2×2) squares and 1 (3×3) square.
Algorithm
To solve this, we will follow these steps ?
- Initialize
resto 0 - For each cell in the matrix:
- If it's in the first row or column, add the cell value to result
- Otherwise, if the cell contains 1, calculate the size of the largest square ending at this position
- Update the cell with this size and add it to the result
- Return the total result
Example
class Solution:
def solve(self, matrix):
res = 0
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if i == 0 or j == 0:
res += matrix[i][j]
elif matrix[i][j] == 1:
matrix[i][j] = min(matrix[i][j - 1], matrix[i - 1][j], matrix[i - 1][j - 1]) + 1
res += matrix[i][j]
return res
ob = Solution()
matrix = [
[1, 1, 1, 0],
[1, 1, 1, 0],
[1, 1, 1, 0],
[0, 0, 0, 0],
[1, 0, 1, 1]
]
print(ob.solve(matrix))
17
How It Works
The algorithm uses dynamic programming where each cell matrix[i][j] stores the side length of the largest square submatrix ending at position (i, j). For any cell, the largest square is determined by the minimum of its three neighbors (left, top, and top-left diagonal) plus 1.
Conclusion
This dynamic programming solution efficiently counts square submatrices by transforming each cell to represent the largest square ending at that position. The time complexity is O(m×n) where m and n are the matrix dimensions.
