# 【LeetCode】 1572. Matrix Diagonal Sum ## Description > 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 not part of the primary diagonal. > Constraints: > * `n == mat.length == mat[i].length` > * `1 <= n <= 100` > * `1 <= mat[i][j] <= 100` > 給予一個方形矩陣 `mat`,回傳該矩陣對角線的和。 > 只包含主對角線上所有元素的和,以及在副對角線卻不在主對角線上所有元素的和。 > 限制: > * `n == mat.length == mat[i].length` > * `1 <= n <= 100` > * `1 <= mat[i][j] <= 100` ## Example: ![](https://hackmd.io/_uploads/BkH2VeUE3.png) ``` Example 1: Input: mat = [[1,2,3], [4,5,6], [7,8,9]] Output: 25 Explanation: Diagonals sum: 1 + 5 + 9 + 3 + 7 = 25 Notice that element mat[1][1] = 5 is counted only once. ``` ``` Example 2: Input: mat = [[1,1,1,1], [1,1,1,1], [1,1,1,1], [1,1,1,1]] Output: 8 ``` ``` Example 3: Input: mat = [[5]] Output: 5 ``` ## Solution * 用一個 for loop 去遍歷兩條對角線的元素並加總 * 你可能會多次使用到矩陣的 size,獨立出來宣告成一個變數儲存會比較省時間 * 加總完之後要考慮當矩陣大小為奇數的時候,最中間的值會被算兩次,因此要減回來 ### Code ```C++=1 class Solution { public: int diagonalSum(vector<vector<int>>& mat) { int count = 0; int s = mat.size(); for(int i = 0; i < s; i++) { count += mat[i][i]; count += mat[s - 1 - i][i]; } if(s % 2 == 1) count -= mat[s / 2][s / 2]; return count; } }; ``` ###### tags: `LeetCode` `C++`