sum of matrix diagonal elements

topic:

Given 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 subdiagonal but not on the main diagonal.

Example:

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
Note that the element mat[1][1] = 5 will only be evaluated once.

Source: LeetCode
Link: https://leetcode.cn/problems/matrix-diagonal-sum

class Solution:
    def diagonalSum(self, mat):
        j=0
        c=1
        a=[]
        b=len(mat)
        for i in mat:
            a.append(i[j])
            a.append(i[len(mat[0])-c])
            c+=1
            j+=1
        d=sum(a)
        if b%2 == 1:
            d-= mat[b/2][b/2]
        return d


 

Guess you like

Origin blog.csdn.net/Tinyfacture/article/details/131964160