Given N which is the size of the N X N spiral matrix of the form:
16 15 14 13 5 4 3 12 6 1 2 11 7 8 9 10
The task is to find the sum of the diagonal elements of this matrix.
Input: N = 3 Output: 25 5 4 3 6 1 2 7 8 9 The sum of elements along its two diagonals will be 1 + 3 + 7 + 5 + 9 = 25 Input: N = 5 Output: 101
Approach: Idea behind the solution is to use the concept of Dynamic Programming. We will use array dp to store our solution. N given in the problem can either be even or odd.
When i is odd, we have to add only 4 corner elements in dp[i – 2].
dp[i] = dp[i – 2] + (i – 2) * (i – 2) + (i – 1) + (i – 2) * (i – 2) + 2 * (i – 1) + (i – 2) * (i – 2) + 3 * (i – 1) + (i – 2) * (i – 2) + 4 * (i – 1)
dp[i] = dp[i – 2] + 4 * (i – 2) * (i – 2) + 10 * (i – 1)
dp[i] = dp[i – 2] + 4 * (i) * (i) – 6 * (i – 1)
Similarly, we can check that the above formula is true when i is even.
Below is the implementation of the above approach:
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Maximum sum of elements in a diagonal parallel to the main diagonal of a given Matrix
- Program to swap upper diagonal elements with lower diagonal elements of matrix.
- Filling diagonal to make the sum of every row, column and diagonal equal of 3x3 matrix
- Convert given Matrix into sorted Spiral Matrix
- Construct a matrix with sum equal to the sum of diagonal elements
- Circular Matrix (Construct a matrix with numbers 1 to m*n in spiral way)
- Construct a square Matrix whose parity of diagonal sum is same as size of matrix
- Program to convert given Matrix to a Diagonal Matrix
- Print matrix elements diagonally in spiral form
- Sum of main diagonal elements in a Matrix which are prime
- Sum of both diagonals of a spiral odd-order square matrix
- Program to find the Product of diagonal elements of a matrix
- Print all the sub diagonal elements of the given square matrix
- Print all the super diagonal elements of the given square matrix
- Program to check diagonal matrix and scalar matrix
- Print a given matrix in reverse spiral form
- Print a given matrix in counter-clock wise spiral form
- Print a given matrix in spiral form using direction tracking method
- Form a Spiral Matrix from the given Array
- Print a given matrix in spiral form
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.