Leetcode.1572 矩阵对角线元素的和

解题思路:
使用一个row变量来记录层数,在循环中使用一个l变量记录左边到右边的值,使用一个r变量记录右边到左边的值,使用width变量记录矩阵的宽度

如图所示,可以通过改变row,l ,r来遍历两个对角线,当l和r相等时,那么就代表走到了两个对角线相交的位置,由于加了两便,所以直接减掉一次就好了,然后就可以完美得到结果
AC代码:
cpp
class Solution {
public:
int diagonalSum(vector<vector<int>>& mat) {
int width=mat[0].size();
int ans=0;
int row=0;
for(int l=0,r=width-1;l<width && r>=0;l++,r--){
if(l==r) ans-=mat[row][l];
ans+=mat[row][l];
ans+=mat[row++][r];
}
return ans;
}
};