diff options
author | jack <[email protected]> | 2024-06-14 13:13:15 -0600 |
---|---|---|
committer | jack <[email protected]> | 2024-06-14 13:13:15 -0600 |
commit | d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa (patch) | |
tree | 96df922dae2a5073d9a50ea70c7aae6aa37e3ebe /matrix_diagonal_sum.cpp | |
download | leetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.tar.gz leetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.zip |
initial
Diffstat (limited to 'matrix_diagonal_sum.cpp')
-rw-r--r-- | matrix_diagonal_sum.cpp | 33 |
1 files changed, 33 insertions, 0 deletions
diff --git a/matrix_diagonal_sum.cpp b/matrix_diagonal_sum.cpp new file mode 100644 index 0000000..d5234b5 --- /dev/null +++ b/matrix_diagonal_sum.cpp @@ -0,0 +1,33 @@ +// 1572. Matrix Diagonal Sum +#include "leetcode.h" + +/* + * given a square matrix 'mat', return the sum of the matrix + * diagonals. only include the sum of all the elements on the + * primary diagonal and all the elements on the secondary + * diagonal that are not part of the primary + */ + +class Solution { +public: + int diagonalSum(vvd(int) & mat) { + int n = mat.size(), ans = 0; + for (int i = 0; i < n; i++) { + if (i != n - i - 1) + ans += mat[i][i] + mat[i][n - i - 1]; + else + ans += mat[i][i]; + } + return ans; + } +}; + +int main() { + Solution obj; + vvd(int) m1 = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; + vvd(int) m2 = {{1, 1, 1, 1}, {1, 1, 1, 1}, {1, 1, 1, 1}, {1, 1, 1, 1}}; + vvd(int) m3 = {{5}}; + printf("%d\n", obj.diagonalSum(m1)); // expect: 25 + printf("%d\n", obj.diagonalSum(m2)); // expect: 8 + printf("%d\n", obj.diagonalSum(m3)); // expect: 5 +} |