Matrix Diagonal Sum
Given a square matrix mat, return the sum of the matrix diagonals.
Only include:
- All elements on the primary diagonal.
- All elements on the secondary diagonal that are not part of the primary diagonal.
Example 1
1 2 3 4 5 6 7 8 9
Input
mat = [[1,2,3],[4,5,6],[7,8,9]]Output
25Diagonals sum to 1 + 5 + 9 + 3 + 7 = 25, with
mat[1][1] = 5 counted only once.Example 2
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
Input
mat = [[1,1,1,1],[1,1,1,1],[1,1,1,1],[1,1,1,1]]Output
8The primary and secondary diagonals contain eight distinct elements, each equal to 1, so the sum is 8.
Constraints
- n == mat.length == mat[i].length
- 1 <= n <= 100
- 1 <= mat[i][j] <= 100