|
| 1 | +/** |
| 2 | + * [1572] Matrix Diagonal Sum |
| 3 | + * |
| 4 | + * Given a square matrix mat, return the sum of the matrix diagonals. |
| 5 | + * 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. |
| 6 | + * |
| 7 | + * Example 1: |
| 8 | + * <img alt="" src="https://assets.leetcode.com/uploads/2020/08/14/sample_1911.png" style="width: 336px; height: 174px;" /> |
| 9 | + * Input: mat = [[1,2,3], |
| 10 | + * [4,5,6], |
| 11 | + * [7,8,9]] |
| 12 | + * Output: 25 |
| 13 | + * Explanation: Diagonals sum: 1 + 5 + 9 + 3 + 7 = 25 |
| 14 | + * Notice that element mat[1][1] = 5 is counted only once. |
| 15 | + * |
| 16 | + * Example 2: |
| 17 | + * |
| 18 | + * Input: mat = [[1,1,1,1], |
| 19 | + * [1,1,1,1], |
| 20 | + * [1,1,1,1], |
| 21 | + * [1,1,1,1]] |
| 22 | + * Output: 8 |
| 23 | + * |
| 24 | + * Example 3: |
| 25 | + * |
| 26 | + * Input: mat = [[5]] |
| 27 | + * Output: 5 |
| 28 | + * |
| 29 | + * |
| 30 | + * Constraints: |
| 31 | + * |
| 32 | + * n == mat.length == mat[i].length |
| 33 | + * 1 <= n <= 100 |
| 34 | + * 1 <= mat[i][j] <= 100 |
| 35 | + * |
| 36 | + */ |
| 37 | +pub struct Solution {} |
| 38 | + |
| 39 | +// problem: https://leetcode.com/problems/matrix-diagonal-sum/ |
| 40 | +// discuss: https://leetcode.com/problems/matrix-diagonal-sum/discuss/?currentPage=1&orderBy=most_votes&query= |
| 41 | + |
| 42 | +// submission codes start here |
| 43 | + |
| 44 | +impl Solution { |
| 45 | + pub fn diagonal_sum(mat: Vec<Vec<i32>>) -> i32 { |
| 46 | + mat.iter().enumerate().fold(0, |sum, (i, row)| { |
| 47 | + sum + row |
| 48 | + .iter() |
| 49 | + .enumerate() |
| 50 | + .filter_map(|(j, n)| (i + j == mat.len() - 1 || i == j).then(|| n)) |
| 51 | + .sum::<i32>() |
| 52 | + }) |
| 53 | + } |
| 54 | +} |
| 55 | + |
| 56 | +// submission codes end |
| 57 | + |
| 58 | +#[cfg(test)] |
| 59 | +mod tests { |
| 60 | + use super::*; |
| 61 | + |
| 62 | + #[test] |
| 63 | + fn test_1572_example_1() { |
| 64 | + let mat = vec![vec![1, 2, 3], vec![4, 5, 6], vec![7, 8, 9]]; |
| 65 | + |
| 66 | + let result = 25; |
| 67 | + |
| 68 | + assert_eq!(Solution::diagonal_sum(mat), result); |
| 69 | + } |
| 70 | + |
| 71 | + #[test] |
| 72 | + fn test_1572_example_2() { |
| 73 | + let mat = vec![ |
| 74 | + vec![1, 1, 1, 1], |
| 75 | + vec![1, 1, 1, 1], |
| 76 | + vec![1, 1, 1, 1], |
| 77 | + vec![1, 1, 1, 1], |
| 78 | + ]; |
| 79 | + |
| 80 | + let result = 8; |
| 81 | + |
| 82 | + assert_eq!(Solution::diagonal_sum(mat), result); |
| 83 | + } |
| 84 | + |
| 85 | + #[test] |
| 86 | + fn test_1572_example_3() { |
| 87 | + let mat = vec![vec![5]]; |
| 88 | + |
| 89 | + let result = 5; |
| 90 | + |
| 91 | + assert_eq!(Solution::diagonal_sum(mat), result); |
| 92 | + } |
| 93 | +} |
0 commit comments