Problem
You are given a 0-indexed integer matrix grid and an integer k.
Return the number of submatrices that contain the top-left element of the grid, and have a sum less than or equal to k.
Algorithm
Dynamic programming (DP): let f[i][j] be the sum of the submatrix from (0,0) to (i,j), and count all positions where f[i][j] ≤ k.
Code
python3
class Solution:
def countSubmatrices(self, grid: List[List[int]], k: int) -> int:
m, n, ans = len(grid), len(grid[0]), 0
for i in range(m):
for j in range(n):
if i > 0:
grid[i][j] += grid[i-1][j]
if j > 0:
grid[i][j] += grid[i][j-1]
if i > 0 and j > 0:
grid[i][j] -= grid[i-1][j-1]
if grid[i][j] <= k:
ans += 1
return ans