Problem Description
Given a binary matrix, count the number of submatrices that contain all ones. A submatrix is any contiguous block of cells within the matrix, and the goal is to count every submatrix where every element is 1.
Key Insights
- Use dynamic programming to build a histogram of consecutive ones for each row.
- For each row, treat the histogram as a base and count submatrices ending at that row.
- Utilize a monotonic stack to efficiently compute the number of valid submatrices based on the histogram heights.
- The key trick is to update the count by considering the minimum height as you extend submatrices to the left.
Space and Time Complexity
Time Complexity: O(m * n) where m is the number of rows and n is the number of columns. Space Complexity: O(n) for the histogram and stack.
Solution
The solution iterates row by row, building a histogram (array of heights) where each entry records the number of consecutive 1's ending at the current row. For each row, the problem of counting submatrices reduces to finding all sub-rectangles in a histogram. A monotonic stack helps to efficiently process each column in the histogram. For each column, while the current height is less than or equal to the top of the stack, we pop from the stack and update the count accordingly; this ensures that we only count submatrices that can extend to the current cell. Finally, the sum of the counts across rows gives the solution.