📜  求给定 NXN 螺旋矩阵的对角线元素之和

📅  最后修改于: 2021-09-22 10:24:59             🧑  作者: Mango

给定N是以下形式的NXN螺旋矩阵的大小:

16 15 14 13
5  4  3  12
6  1  2  11
7  8  9  10

任务是找到这个矩阵的对角元素之和。
例子:

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

方法:解决方案背后的想法是使用动态规划的概念。我们将使用数组dp[]来存储我们的解决方案。问题中给出的 N 可以是偶数也可以是奇数。
i为奇数时,我们只需在dp[i – 2] 中添加 4 个角元素。

类似地,当i偶数时,我们可以检查上述公式是否为真。
下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
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


Javascript


输出:
56

时间复杂度: O(N)
辅助空间: O(N)

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程