Program Statement – Matrix
Diagonal Difference
You are given a square matrix of size N×N. Can you calculate the absolute difference of the sums across the main diagonal and the secondary diagonal?
https://www.hackerrank.com/challenges/diagonal-difference
You are given a square matrix of size N×N. Can you calculate the absolute difference of the sums across the main diagonal and the secondary diagonal?
https://www.hackerrank.com/challenges/diagonal-difference
Program – Python 3 Version
mat = []
nrow = int(input())
for i in
range(nrow):
mat.extend(list(map(int,input().split()))) #keep extending the array
#Main Diagonal Sum
indx,pd_sum = 0,0
for i in
range(nrow):
pd_sum +=
mat[indx]
indx += nrow + 1
#Secondary Diagonal
Sum
indx,sd_sum =
nrow-1,0
for i in
range(nrow):
sd_sum +=
mat[indx]
indx += nrow - 1
print(abs(pd_sum –
sd_sum))
Input -
Input -
3
11 2 4
4 5 6
10 8 -12
Output -
15
Comments