Spiral matrix diagonal element sum

1.3k Views Asked by At

Let n=5, then for matrix

1  2  3  4  5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8 
13 12 11 10 9

then sum of diagonal elements is:

=1+17+25+21+9+5+19+23+13

Sum for n=15?

One way is to make the spiral matrix and then by a loop, we get the answer, but its time and space complexity is large.

Like this https://www.geeksforgeeks.org/sum-diagonals-spiral-odd-order-square-matrix/ but the problem here starts 1 from the center.

2

There are 2 best solutions below

0
On

Based on Bob_'s answer, Here is a recursive code in CPP as requested by OP

int shellcalc(int n,int s){
    if(n==1)
        return s;
    else if(n==0)
        return 0;
    else
    {
        int sum=4*s+(n-1)*6;
        int snew=s+4*(n-1);
        int nnew=n-2;
        return sum+shellcalc(nnew,snew);
    }
}

try it out here https://rextester.com/FLJD46264
Python - https://rextester.com/MDMV32855

0
On

Consider the outer "shell" of the matrix. The sum of the values at the four vertices, given a size of n (5 in your example) and a starting value of s (1 in your example) is

s + (s + (n-1)) + (s + (n-1)*2) + (s + (n-1)*3) = 4*s + (n - 1)*6

The same applies to the inner values, once updated n and s:

s = s + 4 * (n - 1)
n = n - 2

If n becomes less then 2, well, either we have the central element or nothing (n is even).