The Indian Engineer

Problem 1277 Count Square Submatrices with All Ones

Posted on 5 mins

Array Dynamic-Programming Matrix Dp

Problem Statement

Link - Problem 1277

Question

Given a m*n matrix of ones and zeros, return how many square submatrices have all ones.

Example 1:

Input: matrix =
[
  [0,1,1,1],
  [1,1,1,1],
  [0,1,1,1]
]
Output: 15
Explanation: 
There are 10 squares of side 1.
There are 4 squares of side 2.
There is  1 square of side 3.
Total number of squares = 10 + 4 + 1 = 15.

Example 2:

Input: matrix = 
[
  [1,0,1],
  [1,1,0],
  [1,1,0]
]
Output: 7
Explanation: 
There are 6 squares of side 1.  
There is 1 square of side 2. 
Total number of squares = 6 + 1 = 7.

Constraints:

Solution

class Solution {
public:
    int countSquares(vector<vector<int>>& matrix) {
        int row = matrix.size(), col = matrix[0].size();
        vector<vector<int>> dp(row + 1, vector<int>(col + 1, 0));
        int ans = 0;
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                if (matrix[i][j] == 1) {
                    dp[i + 1][j + 1] = min({dp[i][j + 1], dp[i + 1][j], dp[i][j]}) + 1;
                    ans += dp[i + 1][j + 1];
                }
            }
        }
        return ans;
    }
};

Complexity Analysis

| Algorithm                               | Time Complexity | Space Complexity |
| --------------------------------------- | --------------- | ---------------- |
| Dynamic Programming for perfect squares | O(nm)           | O(nm)            |

Explanation

1. Intuition

2. Implementation


Complexity Analysis

Time Complexity:

Space Complexity:


Footnote

This question is rated as Medium difficulty.

Hints

Create an additive table that counts the sum of elements of submatrix with the superior corner at (0,0).

Loop over all subsquares in O(n^3) and check if the sum make the whole array to be ones, if it checks then add 1 to the answer.


Similar Questions:

Title URL Difficulty
Minimum Cost Homecoming of a Robot in a Grid https://leetcode.com/problems/minimum-cost-homecoming-of-a-robot-in-a-grid Medium
Count Fertile Pyramids in a Land https://leetcode.com/problems/count-fertile-pyramids-in-a-land Hard