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