본문 바로가기
알고리즘/leetcode

1572. Matrix Diagonal Sum - python

by 1.5볼트 2023. 5. 8.
728x90

https://leetcode.com/problems/matrix-diagonal-sum/description/

 

Matrix Diagonal Sum - LeetCode

Can you solve this real interview question? Matrix Diagonal Sum - 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 diagonal that are

leetcode.com

행렬의 대각 합을 모두 더하는데 x 형태로 더한다 같은 칸은 중복해서 더하지 않는다 그러므로 같은 칸에 있을 때는 더하지 않음 어차피 아래로 내려가는 거는 같고 0부터 시작하는지 길이에서 0을 빼는지 그 차이다

 

 

class Solution:
    def diagonalSum(self, mat: List[List[int]]) -> int:
        l=len(mat)
        i=j=s=0
        while i<l:
            s+=mat[i][j]
            if j != l-1-j:
                s+=mat[i][l-1-j]
            i+=1
            j+=1
        return s

'알고리즘 > leetcode' 카테고리의 다른 글

59. Spiral Matrix II - python  (0) 2023.05.10
54. Spiral Matrix - python  (0) 2023.05.09
2215. Find the Difference of Two Arrays  (0) 2023.05.03
1822. Sign of the Product of an Array  (0) 2023.05.02
183. Customers Who Never Order  (0) 2023.04.30

댓글