-
Notifications
You must be signed in to change notification settings - Fork 353
/
Copy pathsum_of_all_submatrices.cpp
68 lines (50 loc) · 1.12 KB
/
sum_of_all_submatrices.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
// 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_all_submatrices(vector <vector<int>> grid) {
int m = grid.size() , n = grid[0].size();
int sum = 0;
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
for(int tl = i; tl < m; tl++) {
for(int br = j; br < n; br++) {
for(int r = i; r <= tl; r++) {
for(int c = j; c <= br; c++) {
sum += grid[r][c];
}
}
}
}
}
}
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;
}