AlgoInsight

DSA problem

Count Square Submatrices with All Ones

Medium2D Grid DPPattern: 2D Grid DPtop150AmazonMicrosoftGoogleBloombergAdobe

Given an m x n binary matrix, return the total number of square submatrices that contain only 1s. Submatrices of different sizes and different positions all count separately.

This problem is the counting twin of "Maximal Square." The same recurrence drives both: let dp[i][j] be the side length of the largest all-ones square whose bottom-right corner is (i, j). The crucial observation is that dp[i][j] is not just the size of the biggest square ending here — it is exactly the number of all-ones squares that end here. Why? Because if the largest such square has side s, then squares of side 1, 2, ..., s all also end at (i, j) (each is the bottom-right k x k block of the largest). Each contributes exactly one to the global count.

So the algorithm reuses the Maximal-Square DP: dp[i][j] = 0 if matrix[i][j] == 0, else dp[i][j] = 1 + min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]). The answer is simply the sum of all dp[i][j]. This is a textbook "DP value is also the count of something" identity, and it avoids any separate enumeration of square sizes.

The optimal space-optimized version uses a single 1-D dp array of length n and a prev scalar for the diagonal predecessor, exactly as in Maximal Square — except we accumulate a running total instead of a running max. Total complexity: O(m * n) time and O(n) space.

Examples

Example 1
Input: matrix = [[0,1,1,1],[1,1,1,1],[0,1,1,1]]
Output: 15
Explanation: There are 10 size-1 squares, 4 size-2 squares, and 1 size-3 square, for a total of 15.
Example 2
Input: matrix = [[1,0,1],[1,1,0],[1,1,0]]
Output: 7
Explanation: 6 size-1 squares plus 1 size-2 square = 7.
Example 3
Input: matrix = [[0,0],[0,0]]
Output: 0
Explanation: No 1s anywhere, so no all-ones square exists.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

arraydynamic-programmingmatrix

Browse all DSA problems