MediumNo. 1277

Count Square Submatrices with All Ones — LeetCode 1277 Python Solution

Topics
Array, Dynamic Programming, Matrix
Reading time
3 min

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

PythonSolution
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 ans

Complexity

Time
O(n·m) (typical)
Space · auxiliary
O(n·m)or optimized

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

Related problems
No.ProblemDifficulty
0063Unique Paths IIMedium
0064Minimum Path SumMedium
0085Maximal RectangleHard
0174Dungeon GameHard
0221Maximal SquareMedium
0329Longest Increasing Path in a MatrixHard

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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.