Count Square Submatrices with All Ones — LeetCode 1277 Python Solution
MediumArrayDynamic ProgrammingMatrix
- Problem
- #1277
- Pattern
- Matrix and Grid
- Reading time
- 3 min
- Source
- leetcode.com
The problem
Given a m * n matrix of ones and zeros, return how many square submatrices have all ones.
Example
- Input
- matrix =
- Output
- 15
- Explanation
- There are 10 squares of side 1.
Python solution
Python
class Solution:
def countSquares(self, matrix: List[List[int]]) -> int:
m, n = len(matrix), len(matrix[0])
f = [[0] * n for _ in range(m)]
ans = 0
for i, row in enumerate(matrix):
for j, v in enumerate(row):
if v == 0:
continue
if i == 0 or j == 0:
f[i][j] = 1
else:
f[i][j] = min(f[i - 1][j - 1], f[i - 1][j], f[i][j - 1]) + 1
ans += f[i][j]
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n·m) (typical) |
| Space | O(n·m) or optimized auxiliary |
Pattern: Matrix and Grid
Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 1277. Count Square Submatrices with All Ones is filed here because LeetCode tags it Matrix, which is the vocabulary this hub collects.
The matrix and grid guide has the Python template for the pattern and the 216 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1277. Count Square Submatrices with All Ones?
- LeetCode 1277. Count Square Submatrices with All Ones is rated Medium on LeetCode.
- What topics does LeetCode 1277. Count Square Submatrices with All Ones cover?
- LeetCode 1277. Count Square Submatrices with All Ones is tagged Array, Dynamic Programming and Matrix on LeetCode.