Count Square Submatrices
Let's solve the Count Square Submatrices problem using Dynamic Programming.
Statement
Given a matrix containing only ones and zeros, count the total number of square submatrices that contain only ones.
If the matrix is empty, then return 0.
Constraints:
-
matrix.length
-
matrix[i].length
matrix[i][j]
is either or
Examples
No. | Matrix | Square Submatrices with all Ones |
1 | [ [1, 0, 1] [1, 1, 0] [1, 1, 0] ] | 7 |
2 | [ [1, 1, 1], [1, 1, 1], [1, 1, 1] ] | 14 |
Try it yourself
Implement your solution in the following playground.
import java.util.*;class CountSquareSubmatrices {public static int countSquares(int[][] matrix) {// your code will replace the placeholder return statement belowreturn -1;}}
Note: If you clicked the “Submit” button and the code timed out, this means that your solution needs to be optimized in terms of running time.
Hint: Use dynamic programming and see the magic.
Solution
We will first explore the naive recursive solution to this problem and then see how it can be improved using the 0/1 knapsack dynamic programming pattern.
Naive approach
The naive approach would be to iterate over all the square submatrices and check if they contain all ones.
We iterate over the entire matrix and at each cell, we check if the value is or ...