Open In App

Find the sum of the diagonal elements of the given N X N spiral matrix

Last Updated : 07 Aug, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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.
Examples: 
 

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

 

Recursive Approach: The idea behind the solution is to use recursion to compute sum of the diagonal elements. 

Below is the implementation of the above approach: 

C++




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to return the sum of both the
// diagonal elements of the required matrix
int findSum(int n)
{
    // Base cases
    if(n == 0) {
        return 0;
    }
    if(n == 1) {
        return 1;
    }
     
    int ans = 0;
    // Computing for ans
    for (int i = 2; i <= n; i++) {
        ans =(4 * (i * i))
                - 6 * (i - 1) + findSum(n - 2);
    }
    // Return ans;
    return ans;
}
 
// Driver code
int main()
{
    int n = 4;
 
    cout << findSum(n);
 
    return 0;
}


Java




// Java implementation of the approach
import java.util.*;
 
public class GFG
{
   
// Function to return the sum of both the
// diagonal elements of the required matrix
static int findSum(int n)
{
    // Base cases
    if(n == 0) {
        return 0;
    }
    if(n == 1) {
        return 1;
    }
     
    int ans = 0;
    // Computing for ans
    for (int i = 2; i <= n; i++) {
        ans =(4 * (i * i))
                - 6 * (i - 1) + findSum(n - 2);
    }
    // Return ans;
    return ans;
}
 
// Driver code
public static void main(String args[])
{
    int n = 4;
     
    System.out.println(findSum(n));
     
}
}
// This code is contributed by Samim Hossain Mondal.


Python3




# Python 3 implementation of the approach
 
# Function to return the sum of both the
# diagonal elements of the required matrix
def findSum(n):
 
    # Base cases
    if(n == 0):
        return 0
         
    if(n == 1):
        return 1
     
    ans = 0
    # Computing for ans
    for i in range(2, n + 1, 1):
        ans = ((4 * (i * i)) - 6 *
                      (i - 1) + findSum(n - 2))
 
    return ans
 
# Driver code
if __name__ == '__main__':
    n = 4
 
    print(findSum(n))
 
# This code is contributed by
# Samim Hossain Mondal


C#




// C# implementation of the approach
using System;
 
class GFG
{
   
// Function to return the sum of both the
// diagonal elements of the required matrix
static int findSum(int n)
{
    // Base cases
    if(n == 0) {
        return 0;
    }
    if(n == 1) {
        return 1;
    }
     
    int ans = 0;
    // Computing for ans
    for (int i = 2; i <= n; i++) {
        ans =(4 * (i * i))
                - 6 * (i - 1) + findSum(n - 2);
    }
    // Return ans;
    return ans;
}
 
// Driver code
public static void Main()
{
    int n = 4;
     
    Console.Write(findSum(n));
     
}
}
// This code is contributed by Samim Hossain Mondal.


Javascript




<script>
// Javascript implementation of the approach
 
// Function to return the sum of both the
// diagonal elements of the required matrix
function findSum(n)
{
    // Base cases
    if(n == 0) {
        return 0;
    }
    if(n == 1) {
        return 1;
    }
     
    let ans = 0;
    // Computing for ans
    for (let i = 2; i <= n; i++) {
        ans =(4 * (i * i))
                - 6 * (i - 1) + findSum(n - 2);
    }
    // Return ans;
    return ans;
}
 
// Driver code
let n = 4;
document.write(findSum(n));
 
// This code is contributed by Samim Hossain Mondal.
</script>


Output

56

Time Complexity: O(2N)

Auxiliary Space: O(1)

Dynamic Programming 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: 
 

C++




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to return the sum of both the
// diagonal elements of the required matrix
int findSum(int n)
{
    // Array to store sum of diagonal elements
    int dp[n + 1];
 
    // Base cases
    dp[1] = 1;
    dp[0] = 0;
 
    // Computing the value of dp
    for (int i = 2; i <= n; i++) {
        dp[i] = (4 * (i * i))
                - 6 * (i - 1) + dp[i - 2];
    }
 
    return dp[n];
}
 
// Driver code
int main()
{
    int n = 4;
 
    cout << findSum(n);
 
    return 0;
}


Java




// Java implementation of the approach
class GFG
{
     
// Function to return the sum of both the
// diagonal elements of the required matrix
static int findSum(int n)
{
    // Array to store sum of diagonal elements
    int[] dp = new int[n + 1];
 
    // Base cases
    dp[1] = 1;
    dp[0] = 0;
 
    // Computing the value of dp
    for (int i = 2; i <= n; i++)
    {
        dp[i] = (4 * (i * i)) - 6 *
                    (i - 1) + dp[i - 2];
    }
 
    return dp[n];
}
 
// Driver code
public static void main(String args[])
{
    int n = 4;
 
    System.out.println(findSum(n));
}
}
 
// This code is contributed by Akanksha Rai


Python3




# Python 3 implementation of the approach
 
# Function to return the sum of both the
# diagonal elements of the required matrix
def findSum(n):
     
    # Array to store sum of diagonal elements
    dp = [0 for i in range(n + 1)]
 
    # Base cases
    dp[1] = 1
    dp[0] = 0
 
    # Computing the value of dp
    for i in range(2, n + 1, 1):
        dp[i] = ((4 * (i * i)) - 6 *
                      (i - 1) + dp[i - 2])
 
    return dp[n]
 
# Driver code
if __name__ == '__main__':
    n = 4
 
    print(findSum(n))
 
# This code is contributed by
# Surendra_Gangwar


C#




// C# implementation of the approach
 
class GFG
{
     
// Function to return the sum of both the
// diagonal elements of the required matrix
static int findSum(int n)
{
    // Array to store sum of diagonal elements
    int[] dp = new int[n + 1];
 
    // Base cases
    dp[1] = 1;
    dp[0] = 0;
 
    // Computing the value of dp
    for (int i = 2; i <= n; i++)
    {
        dp[i] = (4 * (i * i))
                - 6 * (i - 1) + dp[i - 2];
    }
 
    return dp[n];
}
 
// Driver code
static void Main()
{
    int n = 4;
 
    System.Console.WriteLine(findSum(n));
}
}
 
// This code is contributed by mits


PHP




<?php
// PHP implementation of the approach
 
// Function to return the sum of both the
// diagonal elements of the required matrix
function findSum($n)
{
     
    // Array to store sum of diagonal elements
    $dp = array();
 
    // Base cases
    $dp[1] = 1;
    $dp[0] = 0;
 
    // Computing the value of dp
    for ($i = 2; $i <= $n; $i++)
    {
        $dp[$i] = (4 * ($i * $i)) - 6 *
                       ($i - 1) + $dp[$i - 2];
    }
 
    return $dp[$n];
}
 
// Driver code
$n = 4;
 
echo findSum($n);
 
// This code is contributed by Akanksha Rai
?>


Javascript




<script>
// Javascript implementation of the approach
 
// Function to return the sum of both the
// diagonal elements of the required matrix
let findSum(n)
{
 
    // Array to store sum of diagonal elements
    let dp = new Array(n + 1);
 
    // Base cases
    dp[1] = 1;
    dp[0] = 0;
 
    // Computing the value of dp
    for (let i = 2; i <= n; i++) {
        dp[i] = (4 * (i * i))
                - 6 * (i - 1) + dp[i - 2];
    }
 
    return dp[n];
}
 
// Driver code
let n = 4;
 
document.write(findSum(n));
 
// This code is contributed by rishavmahato348.
</script>


Output

56

Time Complexity: O(N)
Auxiliary Space: O(N)



Similar Reads

Maximum sum of elements in a diagonal parallel to the main diagonal of a given Matrix
Give a square matrix mat[][] of dimensions N * N, the task is to find the maximum sum of elements present in the given matrix along the diagonals which are parallel to the main diagonal. Below is the image of the same. Examples: Input: mat[][] = {{1, 2, 5, 7}, {2, 6, 7, 3}, {12, 3, 2, 4}, {3, 6, 9, 4}}Output: 18Explanation:Sum of elements present i
11 min read
Program to swap upper diagonal elements with lower diagonal elements of matrix.
Given a square matrix, swap upper diagonal elements of matrix with lower diagonal elements of matrix. Examples : Input: 2 3 5 6 4 5 7 9 8 6 4 9 1 3 5 6 Output: 2 4 8 1 3 5 6 3 5 7 4 5 6 9 9 6 Input: 1 2 3 4 5 6 7 8 9 Output: 1 4 7 2 5 8 3 6 9Recommended PracticeSwapping TrianglesTry It! Below is the implementation of above idea : C/C++ Code // CPP
7 min read
Filling diagonal to make the sum of every row, column and diagonal equal of 3x3 matrix
Given 9 elements in a 3 x 3 matrix where the value of diagonals is 0. We need to find the values in the diagonal to make the sum of every row, column, and diagonal equal. Examples: Input: 0 3 6 5 0 5 4 7 0 Output: 6 3 6 5 5 5 4 7 4 Explanation: Now the value of the sum of any row or column is 15 Input: 0 4 4 4 0 4 4 4 0 Output: 4 4 4 4 4 4 4 4 4 Ap
6 min read
Convert given Matrix into sorted Spiral Matrix
Given a matrix, the task is to convert the given Matrix into sorted Spiral Matrix.Examples: Input: y[][] = { { 2, 5, 12 }, { 22, 54, 55 }, { 1, 6, 8 } }; Output: 1 2 5 45 55 6 22 12 8 Input: y[][] = { { 2, 5, 12 }, { 22, 45, 55 }, { 1, 6, 8 }, { 13, 56, 10 } }; Output: 1 2 5 45 55 6 22 56 8 13 12 10 Approach: Convert the given 2D array into a 1D ar
12 min read
Construct a matrix with sum equal to the sum of diagonal elements
Given an integer N, the task is to construct a matrix of size N2 using positive and negative integers and excluding 0, such that the sum of the matrix is equal to the sum of the diagonal of the matrix. Examples: Input: N = 2 Output: 1 -2 2 4 Explanation: Diagonal sum = (1 + 4) = 5 Matrix sum = (1 - 2 + 2 + 4) = 5 Input: N = 5 Output: 1 2 3 5 10 3 1
4 min read
Construct a square Matrix whose parity of diagonal sum is same as size of matrix
Given an integer N representing the size of the matrix, the task is to construct a square matrix N * N which have an element from 1 to N2 such that the parity of the sum of its diagonals is equal to the parity of integer N. Examples: Input: N = 4Output:1 2 3 4 8 7 6 59 10 11 1216 15 14 13Explanation:Sum of diagonal = 32 and 36 and integer N = 4, al
6 min read
Length of a Diagonal of a Parallelogram using the length of Sides and the other Diagonal
Given two integers A and B, denoting the length of a parallelogram and an integer D, denoting the length of a diagonal, the task is to find the length of another diagonal of the parallelogram. Examples: Input: A = 10, B = 30, D = 20Output: 40.0 Input: A = 6, B = 8, D = 10Output: 10.0 Approach: The relation between sides and diagonals of a parallelo
3 min read
Find diagonal sum of given Matrix when mat[i][j] is product of arr[i] and arr[j]
Given an matrix mat[][] of size N*N (N &gt; 2) such that mat[i][j] = arr[i]*arr[j] (where arr[] is a N sized array that is not provided). The elements along the primary diagonal (top-left to bottom-right) are missing (represented as 0), the task is to find the sum of these missing elements. Examples: Input: N = 5, mat[][] = {{0, 4, 6, 2, 4}, {4, 0,
5 min read
Program to convert given Matrix to a Diagonal Matrix
Given a N*N matrix. The task is to convert the matrix to a diagonal matrix. That is to change the values of the non-diagonal elements of a matrix to 0.Diagonal-Matrix: A matrix is called a Diagonal Matrix if all the non-diagonal elements of the matrix are zero.Examples: Input : mat[][] = {{ 2, 1, 7 }, { 3, 7, 2 }, { 5, 4, 9 }} Output : {{2, 0, 7},
8 min read
Circular Matrix (Construct a matrix with numbers 1 to m*n in spiral way)
Given two values m and n, fill a matrix of size 'm*n' in a spiral (or circular) fashion (clockwise) with natural numbers from 1 to m*n. Examples: Input : m = 4, n = 4 Output : 1 2 3 4 12 13 14 5 11 16 15 6 10 9 8 7 Input : m = 3, n = 4 Output : 1 2 3 4 10 11 12 5 9 8 7 6 The idea is based on Print a given matrix in spiral form. We create a matrix o
10 min read