Count Square Submatrices with All Ones (LeetCode 1277): Solution and Explanation
Given a grid of 0s and 1s, count every square block (of any size) made only of 1s.
Intuition
Checking every possible square directly is slow, since there are O(m * n * min(m, n)) candidates and each takes time to verify.
Give each square a single owner: its bottom-right corner. If the biggest all-ones square ending at a cell has side k, then the squares of side 1, 2, ..., k ending there are all valid, so that cell owns exactly k squares.
A square of side k ending at (i, j) needs squares of side k - 1 ending just above, just to the left and on the diagonal. The weakest of those three neighbours decides how far the square can grow, so k = 1 + min(up, left, diagonal).
Approach: DP on the largest square ending at each cell
- Create
dpof size (m + 1) x (n + 1) filled with 0, so row 0 and column 0 act as a border. - Scan cells row by row. If
matrix[i-1][j-1]is 0, leavedp[i][j] = 0. - Otherwise set
dp[i][j] = 1 + min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]). - Add
dp[i][j]to the running total, since that many squares end at this cell. - Return the total.
Step-by-step example
matrix = [[0,1,1,1],[1,1,1,1],[0,1,1,1]]
- Row 0: dp = [0, 1, 1, 1], total 3. A cell in the top row can only end a 1x1 square.
- Row 1, col 0: dp = 1. Col 1: up 1, left 1, diagonal 0, so dp = 1. Total 5.
- Row 1, col 2: up 1, left 1, diagonal 1, so dp = 2. Col 3 is also 2. Total 9.
- Row 2: col 0 is 0, col 1 gives 1, col 2 gives 1 + min(2, 1, 1) = 2, col 3 gives 1 + min(2, 2, 2) = 3. Total 15.
Code: Python, Java, C++
1class Solution:
2 def countSquares(self, matrix: List[List[int]]) -> int:
3 m, n = len(matrix), len(matrix[0])
4 dp = [[0] * (n + 1) for _ in range(m + 1)]
5 total = 0
6 for i in range(1, m + 1):
7 for j in range(1, n + 1):
8 if matrix[i - 1][j - 1] == 1:
9 dp[i][j] = 1 + min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1])
10 total += dp[i][j]
11 return total1class Solution {
2 public int countSquares(int[][] matrix) {
3 int m = matrix.length, n = matrix[0].length;
4 int[][] dp = new int[m + 1][n + 1];
5 int total = 0;
6 for (int i = 1; i <= m; i++) {
7 for (int j = 1; j <= n; j++) {
8 if (matrix[i - 1][j - 1] == 1) {
9 dp[i][j] = 1 + Math.min(dp[i - 1][j - 1], Math.min(dp[i - 1][j], dp[i][j - 1]));
10 total += dp[i][j];
11 }
12 }
13 }
14 return total;
15 }
16}1class Solution {
2public:
3 int countSquares(vector<vector<int>>& matrix) {
4 int m = matrix.size(), n = matrix[0].size();
5 vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0));
6 int total = 0;
7 for (int i = 1; i <= m; i++) {
8 for (int j = 1; j <= n; j++) {
9 if (matrix[i - 1][j - 1] == 1) {
10 dp[i][j] = 1 + min(dp[i - 1][j - 1], min(dp[i - 1][j], dp[i][j - 1]));
11 total += dp[i][j];
12 }
13 }
14 }
15 return total;
16 }
17};Time and space complexity
O(m * n)
Each cell does a constant amount of work.
O(m * n)
The padded dp table. Only the previous row is needed, so it can drop to O(n), or O(1) by writing into the input matrix.
Other approaches
Brute force (time O(m * n * min(m, n)^2), space O(1))
For every top-left corner, grow the square one size at a time while the new row and column are all ones.
In-place DP (time O(m * n), space O(1))
Overwrite matrix[i][j] with the dp value as you scan, reading the already-updated up, left and diagonal cells.
Common mistakes
- Adding 1 per cell instead of dp[i][j]. Each cell owns every square size from 1 up to dp[i][j].
- Using max instead of min. The smallest neighbour is what limits the square.
- Index errors on the first row and column. The extra padding row and column avoid special cases.
- Confusing this with Maximal Square, which returns the largest area rather than the count.
Frequently asked questions
Why does dp[i][j] equal the number of squares ending at (i, j)?
If a square of side k ends there, so does every smaller square with the same corner, because it is contained in the bigger one. So the squares ending there have sides 1 through dp[i][j], exactly dp[i][j] of them.
How is this related to Maximal Square?
It is the same table. Maximal Square takes the maximum dp value and squares it, while this problem sums all dp values.
Can the answer overflow a 32-bit integer?
No. For a 300 x 300 grid of ones the count is the sum of k^2 for k up to 300, about 9 million, well within int range.