#K42162. Matrix Diagonal Sum
Matrix Diagonal Sum
Matrix Diagonal Sum
Given a square matrix \(A\) of size \(n\times n\), compute the sum of its primary and secondary diagonals. The primary diagonal consists of the elements \(A[i][i]\) for \(i=0,1,\ldots,n-1\) and the secondary diagonal consists of the elements \(A[i][n-1-i]\) for \(i=0,1,\ldots,n-1\). Note that if \(n\) is odd, the center element \(A[\frac{n-1}{2}][\frac{n-1}{2}]\) is counted only once.
Input: The first line contains an integer \(n\) (the size of the matrix). Each of the next \(n\) lines contains \(n\) space-separated integers representing the matrix rows.
Output: Print a single integer that is the sum of the two diagonals of the matrix.
inputFormat
The input is read from standard input and has the following format:
n A[0][0] A[0][1] ... A[0][n-1] A[1][0] A[1][1] ... A[1][n-1] ... A[n-1][0] A[n-1][1] ... A[n-1][n-1]
Where n
is the size of the matrix and each line after that represents a row of the matrix.
outputFormat
Print a single integer to standard output which is the sum of the matrix's primary and secondary diagonals. If the diagonals share a common center element (in the case of an odd-sized matrix), count it only once.
## sample3
1 2 3
4 5 6
7 8 9
25