Given a n * n 2D 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
[Naive Approach] Checking all Submatrices - O(n^6) Time and O(1) Space
The idea is to generate all the possible submatrices and add the sum of all its elements to the result.
// C++ program to find the sum of all possible submatrices
#include <iostream>
#include <vector>
using namespace std;
// Function to find the sum of all submatrices
int matrixSum(vector<vector<int>>& matrix) {
int n = matrix.size();
int res = 0;
// Iterate over all possible top-left corners
for (int startRow = 0; startRow < n; startRow++) {
for (int startCol = 0; startCol < n; startCol++) {
// Iterate over all possible bottom-right corners
for (int endRow = startRow; endRow < n; endRow++) {
for (int endCol = startCol; endCol < n; endCol++) {
// For each valid submatrix, calculate its sum
int submatrixSum = 0;
for (int i = startRow; i <= endRow; i++) {
for (int j = startCol; j <= endCol; j++) {
submatrixSum += matrix[i][j];
}
}
// Add this submatrix sum to the total
res += submatrixSum;
}
}
}
}
return res;
}
int main() {
vector<vector<int>> matrix = {
{1, 1},
{1, 1}
};
cout << matrixSum(matrix);
return 0;
}
// Java program to find the sum of all possible submatrices
import java.util.*;
class GfG {
// Function to find the sum of all submatrices
static int matrixSum(int[][] matrix) {
int n = matrix.length;
int res = 0;
// Iterate over all possible top-left corners
for (int startRow = 0; startRow < n; startRow++) {
for (int startCol = 0; startCol < n; startCol++) {
// Iterate over all possible bottom-right corners
for (int endRow = startRow; endRow < n; endRow++) {
for (int endCol = startCol; endCol < n; endCol++) {
// For each valid submatrix, calculate its sum
int submatrixSum = 0;
for (int i = startRow; i <= endRow; i++) {
for (int j = startCol; j <= endCol; j++) {
submatrixSum += matrix[i][j];
}
}
// Add this submatrix sum to the total
res += submatrixSum;
}
}
}
}
return res;
}
public static void main(String[] args) {
int[][] matrix = {
{1, 1},
{1, 1}
};
System.out.println(matrixSum(matrix));
}
}
# Python program to find the sum of all possible submatrices
# Function to find the sum of all submatrices
def matrixSum(matrix):
n = len(matrix)
res = 0
# Iterate over all possible top-left corners
for startRow in range(n):
for startCol in range(n):
# Iterate over all possible bottom-right corners
for endRow in range(startRow, n):
for endCol in range(startCol, n):
# For each valid submatrix, calculate its sum
submatrixSum = 0
for i in range(startRow, endRow + 1):
for j in range(startCol, endCol + 1):
submatrixSum += matrix[i][j]
# Add this submatrix sum to the total
res += submatrixSum
return res
if __name__ == "__main__":
matrix = [
[1, 1],
[1, 1]
]
print(matrixSum(matrix))
// C# program to find the sum of all possible submatrices
using System;
class GfG {
// Function to find the sum of all submatrices
static int matrixSum(int[][] matrix) {
int n = matrix.Length;
int res = 0;
// Iterate over all possible top-left corners
for (int startRow = 0; startRow < n; startRow++) {
for (int startCol = 0; startCol < n; startCol++) {
// Iterate over all possible bottom-right corners
for (int endRow = startRow; endRow < n; endRow++) {
for (int endCol = startCol; endCol < n; endCol++) {
// For each valid submatrix, calculate its sum
int submatrixSum = 0;
for (int i = startRow; i <= endRow; i++) {
for (int j = startCol; j <= endCol; j++) {
submatrixSum += matrix[i][j];
}
}
// Add this submatrix sum to the total
res += submatrixSum;
}
}
}
}
return res;
}
static void Main(string[] args) {
int[][] matrix = new int[][] {
new int[] {1, 1},
new int[] {1, 1}
};
Console.WriteLine(matrixSum(matrix));
}
}
// JavaScript program to find the sum of all possible submatrices
// Function to find the sum of all submatrices
function matrixSum(matrix) {
let n = matrix.length;
let res = 0;
// Iterate over all possible top-left corners
for (let startRow = 0; startRow < n; startRow++) {
for (let startCol = 0; startCol < n; startCol++) {
// Iterate over all possible bottom-right corners
for (let endRow = startRow; endRow < n; endRow++) {
for (let endCol = startCol; endCol < n; endCol++) {
// For each valid submatrix, calculate its sum
let submatrixSum = 0;
for (let i = startRow; i <= endRow; i++) {
for (let j = startCol; j <= endCol; j++) {
submatrixSum += matrix[i][j];
}
}
// Add this submatrix sum to the total
res += submatrixSum;
}
}
}
}
console.log(res);
}
let matrix = [
[1, 1],
[1, 1]
];
matrixSum(matrix);
Output
16
[Expected Approach] Using Reverse Lookup - O(n^2) Time and O(1) Space
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:
- For each element at position (i ,j), calculate how many different top-left corners could form a submatrix containing it: (i+1)*(j+1).
- Calculate how many different bottom-right corners could form a submatrix containing it: (n-i)*(n-j).
- The total number of submatrices containing this element is the product: (i + 1)(j + 1)(n - i)*(n - j).
- Multiply this count by the element's value to get its total contribution to the sum.
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
// C++ program to find the sum of all possible submatrices
#include <iostream>
#include <vector>
using namespace std;
// Function to find the sum of all submatrices
int matrixSum(vector<vector<int>>& matrix) {
int n = matrix.size();
int res = 0;
// Iterate through each element in the matrix
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
// Number of ways to choose the top-left corner
int topLeft = (i + 1) * (j + 1);
// Number of ways to choose the bottom-right corner
int bottomRight = (n - i) * (n - j);
// Calculate contribution of current element
res += (topLeft * bottomRight * matrix[i][j]);
}
}
return res;
}
int main() {
vector<vector<int>> matrix = {
{1, 1},
{1, 1}
};
cout << matrixSum(matrix);
return 0;
}
// Java program to find the sum of all possible submatrices
import java.util.*;
class GfG {
// Function to find the sum of all submatrices
static int matrixSum(int[][] matrix) {
int n = matrix.length;
int res = 0;
// Iterate through each element in the matrix
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
// Number of ways to choose the top-left corner
int topLeft = (i + 1) * (j + 1);
// Number of ways to choose the bottom-right corner
int bottomRight = (n - i) * (n - j);
// Calculate contribution of current element
res += (topLeft * bottomRight * matrix[i][j]);
}
}
return res;
}
public static void main(String[] args) {
int[][] matrix = {
{1, 1},
{1, 1}
};
System.out.println(matrixSum(matrix));
}
}
# Python program to find the sum of all possible submatrices
# Function to find the sum of all submatrices
def matrixSum(matrix):
n = len(matrix)
res = 0
# Iterate through each element in the matrix
for i in range(n):
for j in range(n):
# Number of ways to choose the top-left corner
topLeft = (i + 1) * (j + 1)
# Number of ways to choose the bottom-right corner
bottomRight = (n - i) * (n - j)
# Calculate contribution of current element
res += (topLeft * bottomRight * matrix[i][j])
return res
if __name__ == "__main__":
matrix = [
[1, 1],
[1, 1]
]
print(matrixSum(matrix))
// C# program to find the sum of all possible submatrices
using System;
class GfG {
// Function to find the sum of all submatrices
static int matrixSum(int[][] matrix) {
int n = matrix.Length;
int res = 0;
// Iterate through each element in the matrix
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
// Number of ways to choose the top-left corner
int topLeft = (i + 1) * (j + 1);
// Number of ways to choose the bottom-right corner
int bottomRight = (n - i) * (n - j);
// Calculate contribution of current element
res += (topLeft * bottomRight * matrix[i][j]);
}
}
return res;
}
static void Main(string[] args) {
int[][] matrix = new int[][] {
new int[] {1, 1},
new int[] {1, 1}
};
Console.WriteLine(matrixSum(matrix));
}
}
// JavaScript program to find the sum of all possible submatrices
// Function to find the sum of all submatrices
function matrixSum(matrix) {
let n = matrix.length;
let res = 0;
// Iterate through each element in the matrix
for (let i = 0; i < n; i++) {
for (let j = 0; j < n; j++) {
// Number of ways to choose the top-left corner
let topLeft = (i + 1) * (j + 1);
// Number of ways to choose the bottom-right corner
let bottomRight = (n - i) * (n - j);
// Calculate contribution of current element
res += (topLeft * bottomRight * matrix[i][j]);
}
}
return res;
}
let matrix = [
[1, 1],
[1, 1]
];
console.log(matrixSum(matrix));
Output
16