![]() |
VOOZH | about |
Given a n * n2D matrix, the task to find the sum of all the submatrices.
Examples:
Input : mat[][] = [[1, 1],
[1, 1]];
Output : 16
Explanation:
Number of sub-matrices with 1 elements = 4
Number of sub-matrices with 2 elements = 4
Number of sub-matrices with 3 elements = 0
Number of sub-matrices with 4 elements = 1
Since all the entries are 1, the sum becomes
sum = 1 * 4 + 2 * 4 + 3 * 0 + 4 * 1 = 16
Input : mat[][] = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
Output : 500
The idea is to generate all the possible submatrices and add the sum of all its elements to the result.
16
The idea is to calculate the contribution of each element to the total sum by determining in how many different submatrices that element appears. We can directly compute how many submatrices contain each element in O(1) time and use this to find each element's total contribution to the sum.
Step by step approach:
Illustration:
Taking example of matrix:
[1 2 3]
[4 5 6]
[7 8 9]Let's consider the element 5 at position (1,1) in a 3×3 matrix:
- Possible top-left corners: (0,0), (0,1), (1,0), (1,1) → (1+1)*(1+1) = 4 possibilities
- Possible bottom-right corners: (1,1), (1,2), (2,1), (2,2) → (3-1)*(3-1) = 4 possibilities
- Total submatrices containing 5: 4×4 = 16 submatrices
- Total contribution of element 5 to the sum: 5×16 = 80
16