Problem Description
Given a 0-indexed integer matrix grid and an integer k, count the number of submatrices that contain the top-left element of grid (i.e. submatrices that start at (0,0)) and have a sum less than or equal to k.
Key Insights
- Only submatrices that include the top-left element (0,0) are considered. This means every valid submatrix can be uniquely defined by its bottom-right corner (i, j).
- The sum of the submatrix from (0,0) to (i,j) can be efficiently computed using a 2D prefix sum (cumulative sum) matrix.
- Given the constraints and non-negativity of grid elements, we can compute these prefix sums in O(m*n) time and simply count those that meet the requirement.
Space and Time Complexity
Time Complexity: O(m * n)
Space Complexity: O(m * n)
Solution
The solution leverages a 2D prefix sum array to compute the sum of the submatrix from the top-left element (0,0) to any point (i,j) in constant time after preprocessing. The prefix sum for cell (i, j) is computed as: prefix[i][j] = grid[i][j] + (prefix[i-1][j] if i > 0 else 0) + (prefix[i][j-1] if j > 0 else 0) - (prefix[i-1][j-1] if i > 0 and j > 0 else 0) Then, iterate over all cells and count the number of positions where prefix[i][j] <= k.