Given a matrix of M x N elements (M rows, N columns), return all elements of the matrix in diagonal order as shown in the below image. Example: Input:[[ 1, 2, 3 ],[ 4, 5, 6 ],[ 7, 8, 9 ]]Output:
文章目录 一、题目二、题解 一、题目 Given a square matrix mat, return the sum of the matrix diagonals. Only include the sum of all the elements on the primary diagonal and all the elements on the secondary
注意行列数为奇数时,需要减去中心的位置的值,因为其被加和了两次。 class Solution:def diagonalSum(self, mat: List[List[int]]) -> int:res = 0for i, j in zip(range(len(mat)), range(len(mat[0]))):res += mat[i][j]for i in range(len(mat))