-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1572-matrix_diagonal_sum.cpp
43 lines (42 loc) · 1.07 KB
/
1572-matrix_diagonal_sum.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
// Approach - 1
class Solution {
public:
int diagonalSum(vector<vector<int>>& mat) {
int n = mat.size();
int sum1 = 0, sum2 = 0, sum = 0;
if(n % 2 != 0) {
for(int i=0; i<n; i++) {
for(int j=0; j<n; j++) {
if(i == j) sum1 += mat[i][j];
if(i == n - j - 1) sum2 += mat[i][j];
}
}
sum = sum1 + sum2 - mat[n/2][n/2];
}
else {
for(int i=0; i<n; i++) {
for(int j=0; j<n; j++) {
if(i == j) sum1 += mat[i][j];
if(i == n - j - 1) sum2 += mat[i][j];
}
}
sum = sum1 + sum2;
}
return sum;
}
};
// Approach - 2
class Solution {
public:
int diagonalSum(vector<vector<int>>& mat) {
int n = mat.size();
int sum = 0;
for (int i = 0; i < n; i++) {
sum += mat[i][i];
if (i != n - i - 1) {
sum += mat[i][n - i - 1];
}
}
return sum;
}
};