반응형
https://leetcode.com/problems/matrix-diagonal-sum/
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
각 대각선의 합을 구해줍니다. 매트릭스의 길이가 홀수일 때에는, 중앙에 있는 값을 차감해줍니다.
class Solution {
public:
int diagonalSum(vector<vector<int>>& mat) {
int n = mat.size();
int s = n % 2 ? -mat[n/2][n/2] : 0;
for(int i=0; i<n; i++) {
s += mat[i][i] + mat[i][n - i - 1];
}
return s;
}
};
반응형
'Algorithm' 카테고리의 다른 글
LeetCode 1035. Uncrossed Lines (0) | 2023.05.11 |
---|---|
LeetCode 54. Spiral Matrix (0) | 2023.05.09 |
LeetCode 1964. Find the Longest Valid Obstacle Course at Each Position (0) | 2023.05.07 |
LeetCode 1498. Number of Subsequences That Satisfy the Given Sum Condition (1) | 2023.05.06 |
LeetCode 1456. Maximum Number of Vowels in a Substring of Given Length (0) | 2023.05.05 |