1572. Matrix Diagonal Sum
https://leetcode.com/problems/matrix-diagonal-sum/description/
算出所有对角线元素的总和。
Example 1:
https://assets.leetcode.com/uploads/2020/08/14/sample_1911.png
Input: mat = [[1,2,3],
[4,5,6],
[7,8,9]]
Output: 25
Explanation: Diagonals sum: 1 + 5 + 9 + 3 + 7 = 25
Notice that element mat[1][1] = 5 is counted only once.
Example 2:
Input: mat = [[1,1,1,1],
[1,1,1,1],
[1,1,1,1],
[1,1,1,1]]
Output: 8
思路:
1.mat[i][j]对角线上的元素只有两种情况满足,i == j 或 i + j = n - 1
遍历的时候满足条件就加起来就好。
Java Code: