## The sum of diagonal elements of matrix Java

Princess SINB 2020-11-13 05:15:34
sum diagonal elements matrix java

Here's a square matrix mat, Please return the sum of the diagonal elements of the matrix .
Please return the sum of the elements on the main diagonal and the sub diagonal of the matrix and not on the main diagonal .

`````` Example 1：
Input ：mat = [[1,2,3],
[4,5,6],
[7,8,9]]
Output ：25
explain ： The sum of diagonals is ：1 + 5 + 9 + 3 + 7 = 25
Please note that , Elements mat[1][1] = 5 Will only be counted once .
Example 2：
Input ：mat = [[1,1,1,1],
[1,1,1,1],
[1,1,1,1],
[1,1,1,1]]
Output ：8
Example 3：
Input ：mat = [[5]]
Output ：5
Tips ：
n == mat.length == mat[i].length
1 <= n <= 100
1 <= mat[i][j] <= 100
source ： Power button （LeetCode）
``````
``````class Solution {

public int diagonalSum(int[][] mat) {

int row=mat.length;
int sum=0;
for(int i=0;i<row;i++) sum+=mat[i][i];
for(int i=0,j=row-1;i<row;i++,j--)sum+=mat[i][j];
if(row%2==1)
{

int mid=row/2;
sum-=mat[mid][mid];
}
return sum;
}
}
``````