Given a m * n matrix of ones and zeros, return how many square submatrices have all ones.
Input:
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.
Input:
Output: 7
Explanation:
There are 6 squares of side 1.
There is 1 square of side 2.
Total number of squares = 6 + 1 = 7.
1 <= arr.length <= 3001 <= arr[0].length <= 3000 <= arr[i][j] <= 1The basic idea is to count all possible square submatrices in the matrix that have all ones. The brute force approach involves iterating over every potential square submatrix and checking if it consists entirely of ones.
1.This approach checks every possible square matrix, and hence can be quite inefficient for larger matrices.
The dynamic programming approach incrementally builds a solution using previous results. The key insight is recognizing that the size of the square submatrix ending at position (i, j) can be determined by the smallest square ending at positions (i-1, j), (i, j-1), and (i-1, j-1), if (i, j) itself is 1.
dp[i][j] represents the size of the largest square submatrix with all ones ending at (i, j).