Problem Description
Given an m x n binary matrix (with values 0 and 1), the task is to count the number of square submatrices that have all ones. Each submatrix must be square and completely filled with ones.
Key Insights
- Use dynamic programming to solve the problem.
- Create a dp table where each dp[i][j] represents the size of the largest square that ends at cell (i, j).
- For a cell containing one, the potential square size is determined by taking the minimum of its top, left, and top-left neighbors, then adding one.
- Accumulate the value of dp[i][j] to get the total count of square submatrices with all ones.
- Handling boundary conditions where the cell is in the first row or column is essential.
Space and Time Complexity
Time Complexity: O(m * n)
Space Complexity: O(m * n) (this can be optimized to O(n) if modifying the original matrix is allowed)
Solution
We solve the problem using dynamic programming. For each cell in the matrix that contains a one, we determine the size of the maximal square submatrix ending at that cell by looking at its top, left, and top-left neighbors in the dp table. The cell's dp value will be one plus the minimum of these three values. The final answer is the sum of all values in the dp table, which represent the count of squares ending at each position.