classSolution { public: intcountSubmatrices(vector<vector<int>>& grid, int k){ int m = grid.size(), n = grid[0].size(), count = 0; // Prefix Sum vector<vector<int>> prefix(m, vector<int>(n, 0)); for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { int sum = grid[i][j]; if (i > 0) sum += prefix[i - 1][j]; if (j > 0) sum += prefix[i][j - 1]; if (i > 0 && j > 0) sum -= prefix[i - 1][j - 1]; prefix[i][j] = sum; if (sum <= k) ++count; // Count single cell } }
// Check all possible submatrices for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { for (int p = i; p < m; ++p) { for (int q = j; q < n; ++q) { int submatrix_sum = prefix[p][q]; if (i > 0) submatrix_sum -= prefix[i - 1][q]; if (j > 0) submatrix_sum -= prefix[p][j - 1]; if (i > 0 && j > 0) submatrix_sum += prefix[i - 1][j - 1]; if (submatrix_sum <= k) ++count; } } } }
// Deduct the single cells which are counted in the first time return count - m * n; } };
intmain(){ Solution s; vector<vector<int>> grid = {{7,2,9},{1,5,0},{2,6,6}}; int k = 20; cout << "The number of submatrices is: " << s.countSubmatrices(grid, k) << endl; return0; }