Skip to content

Commit 5814e6e

Browse files
committed
sum_of_all_submatrices_3.cpp file added
1 parent bf31640 commit 5814e6e

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
// Problem - Print the sum of all submatrices of the given matrix
2+
3+
// Sample Input - 1
4+
// 3 3
5+
// 1 1 1
6+
// 1 1 1
7+
// 1 1 1
8+
9+
// Sample Output - 1
10+
// 100
11+
12+
// Sample Input - 2
13+
// 3 2
14+
// 1 10 8
15+
// -1 5 0
16+
17+
// Sample Output - 2
18+
// 152
19+
20+
#include <iostream>
21+
#include <vector>
22+
23+
using namespace std;
24+
25+
26+
int sum_of_all_submatrices(vector <vector <int>> grid) {
27+
28+
// Contribution of an element to the sum is defined as at index (i , j) of matrix with order n * m:
29+
// value * (i + 1) * (j + 1) * (n - i) * (m - j)
30+
31+
// Time Complexity: O(n ^ 2)
32+
// Auxiliary Space Complexity: O(1)
33+
34+
35+
int n = grid.size();
36+
int m = grid[0].size();
37+
int sum = 0;
38+
39+
40+
// Traversing the matrix
41+
for(int i = 0; i < n; i++) {
42+
for(int j = 0; j < m; j++) {
43+
44+
// Calculating the contribution of an element to the sum and adding it to the sum
45+
sum += grid[i][j] * (i + 1) * (j + 1) * (n - i) * (m - j);
46+
}
47+
}
48+
49+
return sum;
50+
51+
}
52+
53+
int main() {
54+
55+
int m , n;
56+
cout << "Enter the no. of rows and columns : " << endl;
57+
cin >> m >> n;
58+
59+
vector <vector <int>> grid(m , vector<int> (n));
60+
cout << "Enter the elements of the matrix : " << endl;
61+
for (int i = 0; i < m; i++) {
62+
for (int j = 0; j < n; j++) {
63+
cin >> grid[i][j];
64+
}
65+
}
66+
67+
int sum = sum_all_submatrices(grid);
68+
69+
cout << "The sum of all submatrices of the given matrix is : " << sum << endl;
70+
71+
return 0;
72+
}

0 commit comments

Comments
 (0)