
Input: grid =[[7,6,3],[6,6,1]], k =18Output: 4Explanation: There are only 4 submatrices, shown in the image above, that contain the top-left element of grid, and have a sum less than or equal to 18.

Input: grid =[[7,2,9],[1,5,0],[2,6,6]], k =20Output: 6Explanation: There are only 6 submatrices, shown in the image above, that contain the top-left element of grid, and have a sum less than or equal to 20.
We want to count all submatrices that start at the top-left (0,0) and end at (i,j) for all i, j, such that the sum of the submatrix is less than or equal to k. By precomputing prefix sums, we can quickly get the sum of any such submatrix.
classSolution {
publicintcountSubmatrices(int[][] grid, int k) {
int n = grid.length, m = grid[0].length, ans = 0;
int[][] ps =newint[n+1][m+1];
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= m; ++j) {
ps[i][j]= grid[i-1][j-1]+ ps[i-1][j]+ ps[i][j-1]- ps[i-1][j-1];
if (ps[i][j]<= k) ans++;
}
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
classSolution {
funcountSubmatrices(grid: Array<IntArray>, k: Int): Int {
val n = grid.size
val m = grid[0].size
val ps = Array(n+1) { IntArray(m+1) }
var ans = 0for (i in1..n) {
for (j in1..m) {
ps[i][j] = grid[i-1][j-1] + ps[i-1][j] + ps[i][j-1] - ps[i-1][j-1]
if (ps[i][j] <= k) ans++ }
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
classSolution:
defcountSubmatrices(self, grid: list[list[int]], k: int) -> int:
n, m = len(grid), len(grid[0])
ps = [[0]*(m+1) for _ in range(n+1)]
ans =0for i in range(1, n+1):
for j in range(1, m+1):
ps[i][j] = grid[i-1][j-1] + ps[i-1][j] + ps[i][j-1] - ps[i-1][j-1]
if ps[i][j] <= k:
ans +=1return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
impl Solution {
pubfncount_submatrices(grid: Vec<Vec<i32>>, k: i32) -> i32 {
let n = grid.len();
let m = grid[0].len();
letmut ps =vec![vec![0; m+1]; n+1];
letmut ans =0;
for i in1..=n {
for j in1..=m {
ps[i][j] = grid[i-1][j-1] + ps[i-1][j] + ps[i][j-1] - ps[i-1][j-1];
if ps[i][j] <= k {
ans +=1;
}
}
}
ans
}
}