#K57537. Diagonal Sum of Matrix Diagonals
Diagonal Sum of Matrix Diagonals
Diagonal Sum of Matrix Diagonals
You are given a square matrix of size \(n \times n\) containing integers. Your task is to compute the sum of the elements on the main diagonal and the anti-diagonal. Note that if \(n\) is odd, the center element (which belongs to both diagonals) should only be counted once.
Example:
Input: 3 1 2 3 4 5 6 7 8 9</p>Output: 25
In the 3x3 matrix above, the main diagonal elements are \(1, 5, 9\) and the anti-diagonal elements are \(3, 5, 7\). Since \(5\) is the center element and would be counted twice, it is only added once. Therefore, the total sum is \(1 + 5 + 9 + 3 + 7 - 5 = 25\).
inputFormat
The first line of input contains a single integer \(n\) which represents the size of the matrix. This is followed by \(n\) lines each containing \(n\) space-separated integers representing the rows of the matrix.
outputFormat
Output a single integer representing the sum of the elements in the main and anti-diagonals of the matrix, counting the center element only once if \(n\) is odd.
## sample3
1 2 3
4 5 6
7 8 9
25
</p>