A matrix in Python is just a list of lists: mat[r] is row r and mat[r][c] is the cell in row r, column c. For a square matrix with n rows, the primary diagonal runs from the top-left to the bottom-right, and the secondary diagonal runs from the top-right to the bottom-left.
Given a square matrix mat, return the sum of the elements on the primary diagonal plus the elements on the secondary diagonal that are not already on the primary diagonal.
Examples
Input: mat = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
Output: 25
Explanation: 1 + 5 + 9 (primary) + 3 + 7 (secondary). The centre 5 is counted once.
Input: mat = [[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1]]
Output: 8
Constraints
mathasnrows andncolumns,1 <= n <= 50-100 <= mat[r][c] <= 100
Goals
- Index a 2D list with mat[row][col]
- Derive the column of a diagonal cell from its row number
- Avoid double counting a cell that lies on both diagonals