
Problem
Solution
Submissions
Count of Submatrices
Certification: Advanced Level
Accuracy: 0%
Submissions: 0
Points: 15
Write a C program to find the number of non-empty submatrices that sum to a given target value. A submatrix is a rectangular region within the matrix. You need to count all possible submatrices (including single elements) whose sum equals the target.
Example 1
- Input: matrix = [[0,1,0],[1,1,1],[0,1,0]], target = 0
- Output: 4
- Explanation:
- There are 4 submatrices that sum to 0.
- Single elements: matrix[0][0] = 0, matrix[0][2] = 0, matrix[2][0] = 0, matrix[2][2] = 0.
- These 4 submatrices each have sum = 0.
- Therefore, answer is 4.
- There are 4 submatrices that sum to 0.
Example 2
- Input: matrix = [[1,-1],[-1,1]], target = 0
- Output: 5
- Explanation:
- Submatrices with sum 0 are: [1,-1] (first row), [-1,1] (second row), [1;-1] (first column), [-1;1](secondcolumn).
- And the entire 2x2 matrix [[1,-1],[-1,1]].
- Total count = 5 submatrices.
Constraints
- 1 ≤ matrix.length ≤ 100
- 1 ≤ matrix[0].length ≤ 100
- -1000 ≤ matrix[i][j] ≤ 1000
- -10^8 ≤ target ≤ 10^8
- Time Complexity: O(m^2 * n^2)
- Space Complexity: O(n)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use prefix sum technique to calculate submatrix sums efficiently
- Fix top and bottom rows, then use 1D subarray sum technique
- For each column range, maintain running sum and use hash map
- Count subarrays with target sum using the difference technique
- Iterate through all possible top-bottom row combinations