[LeetCode] 1572. The sum of diagonal elements of a matrix (C++)

1 topic description

Give you 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 of the matrix and the elements on the sub-diagonal and not on the main diagonal.

2 Example description

2.1 Example 1

Input: mat = [[1,2,3], [4,5,6], [7,8,9]]
Output: 25
Explanation: The sum of the diagonals is: 1 + 5 + 9 + 3 + 7 = 25
Please note that the element mat[1][1] = 5 will only be calculated once.
Insert picture description here

2.2 Example 2

Input: mat =
[[1,1,1,1],
[1,1,1,1],
[1,1,1,1],
[1,1,1,1]]
Output: 8

2.3 Example 3

Input: mat = [[5]]
Output: 5

3 Problem solving tips

n == mat.length == mat[i].length
1 <= n <= 100
1 <= mat[i][j] <= 100

4 Detailed source code (C++)

class Solution {
    
    
public:
    int diagonalSum(vector<vector<int>>& mat) {
    
    
        int res = 0 ;
        if ( mat.size() % 2 == 0)
        {
    
    
            for (int i = 0 ; i < mat.size() ; i ++)
            {
    
    
                for (int j = 0 ; j < mat.size() ; j ++)
                {
    
    
                    if ( i == j || i + j == (mat.size() - 1))
                    {
    
    
                        res = res + mat[i][j];
                    }
                }
            }
        }
        else
        {
    
    
            for (int i = 0 ; i < mat.size() ; i ++)
            {
    
    
                for (int j = 0 ; j < mat.size() ; j ++)
                {
    
    
                    if ( i == j || i + j == (mat.size() - 1))
                    {
    
    
                        res = res + mat[i][j];
                    }
                }
            }
        }
        return res;
    }
};

Guess you like

Origin blog.csdn.net/Gyangxixi/article/details/114018195