|
| 1 | +# [1572. Matrix Diagonal Sum](https://leetcode.com/problems/matrix-diagonal-sum) |
| 2 | + |
| 3 | +[中文文档](/solution/1500-1599/1572.Matrix Diagonal Sum/README.md) |
| 4 | + |
| 5 | +## Description |
| 6 | + |
| 7 | +<p>Given a square matrix <code>mat</code>, return the sum of the matrix diagonals.</p> |
| 8 | + |
| 9 | +<p>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.</p> |
| 10 | + |
| 11 | +<p> </p> |
| 12 | +<p><strong>Example 1:</strong></p> |
| 13 | +<img alt="" src="https://assets.leetcode.com/uploads/2020/08/14/sample_1911.png" style="width: 336px; height: 174px;" /> |
| 14 | +<pre> |
| 15 | +<strong>Input:</strong> mat = [[<strong>1</strong>,2,<strong>3</strong>], |
| 16 | + [4,<strong>5</strong>,6], |
| 17 | + [<strong>7</strong>,8,<strong>9</strong>]] |
| 18 | +<strong>Output:</strong> 25 |
| 19 | +<strong>Explanation: </strong>Diagonals sum: 1 + 5 + 9 + 3 + 7 = 25 |
| 20 | +Notice that element mat[1][1] = 5 is counted only once. |
| 21 | +</pre> |
| 22 | + |
| 23 | +<p><strong>Example 2:</strong></p> |
| 24 | + |
| 25 | +<pre> |
| 26 | +<strong>Input:</strong> mat = [[<strong>1</strong>,1,1,<strong>1</strong>], |
| 27 | + [1,<strong>1</strong>,<strong>1</strong>,1], |
| 28 | + [1,<strong>1</strong>,<strong>1</strong>,1], |
| 29 | + [<strong>1</strong>,1,1,<strong>1</strong>]] |
| 30 | +<strong>Output:</strong> 8 |
| 31 | +</pre> |
| 32 | + |
| 33 | +<p><strong>Example 3:</strong></p> |
| 34 | + |
| 35 | +<pre> |
| 36 | +<strong>Input:</strong> mat = [[<strong>5</strong>]] |
| 37 | +<strong>Output:</strong> 5 |
| 38 | +</pre> |
| 39 | + |
| 40 | +<p> </p> |
| 41 | +<p><strong>Constraints:</strong></p> |
| 42 | + |
| 43 | +<ul> |
| 44 | + <li><code>n == mat.length == mat[i].length</code></li> |
| 45 | + <li><code>1 <= n <= 100</code></li> |
| 46 | + <li><code>1 <= mat[i][j] <= 100</code></li> |
| 47 | +</ul> |
| 48 | + |
| 49 | + |
| 50 | +## Solutions |
| 51 | + |
| 52 | + |
| 53 | + |
| 54 | +<!-- tabs:start --> |
| 55 | + |
| 56 | +### **Python3** |
| 57 | + |
| 58 | + |
| 59 | +```python |
| 60 | + |
| 61 | +``` |
| 62 | + |
| 63 | +### **Java** |
| 64 | + |
| 65 | + |
| 66 | +```java |
| 67 | + |
| 68 | +``` |
| 69 | + |
| 70 | +### **...** |
| 71 | +``` |
| 72 | +
|
| 73 | +``` |
| 74 | + |
| 75 | +<!-- tabs:end --> |
0 commit comments