螺旋奇数阶方阵的两条对角线之和
我们给出了一个奇数阶的螺旋矩阵,其中我们以数字 1 为中心,顺时针向右移动。
例子 :
Input : n = 3
Output : 25
Explanation : spiral matrix =
7 8 9
6 1 2
5 4 3
The sum of diagonals is 7+1+3+9+5 = 25
Input : n = 5
Output : 101
Explanation : spiral matrix of order 5
21 22 23 23 25
20 7 8 9 10
19 6 1 2 11
18 5 4 3 12
17 16 15 14 13
The sum of diagonals is 21+7+1+3+13+
25+9+5+17 = 101
如果我们仔细观察 nxn 的螺旋矩阵,我们可以注意到右上角元素的值为 n 2 。左上角的值为 (n^2) – (n-1) [为什么?不是我们在螺旋矩阵中逆时针移动,因此我们从右上角减去 n-1 后得到左上角的值]。类似地,左下角的值为 (n^2) – 2(n-1),右下角的值为 (n^2) – 3(n-1)。添加所有四个角后,我们得到 4[(n^2)] – 6(n-1)。
令 f(n) 为 anxn 矩阵的对角线元素之和。使用上述观察,我们可以递归地将 f(n) 写为:
f(n) = 4[(n^2)] – 6(n-1) + f(n-2)
由上述关系式,我们可以借助迭代法求出一个螺旋矩阵的所有对角线元素之和。
spiralDiaSum(n)
{
if (n == 1)
return 1;
// as order should be only odd
// we should pass only odd-integers
return (4*n*n - 6*n + 6 + spiralDiaSum(n-2));
}
下面是实现。
C++
// C++ program to find sum of
// diagonals of spiral matrix
#include
using namespace std;
// function returns sum of diagonals
int spiralDiaSum(int n)
{
if (n == 1)
return 1;
// as order should be only odd
// we should pass only odd-integers
return (4*n*n - 6*n + 6 + spiralDiaSum(n-2));
}
// Driver program
int main()
{
int n = 7;
cout << spiralDiaSum(n);
return 0;
}
Java
// Java program to find sum of
// diagonals of spiral matrix
class GFG
{
// function returns sum of diagonals
static int spiralDiaSum(int n)
{
if (n == 1)
return 1;
// as order should be only odd
// we should pass only odd-integers
return (4 * n * n - 6 * n + 6 +
spiralDiaSum(n - 2));
}
// Driver program to test
public static void main (String[] args)
{
int n = 7;
System.out.print(spiralDiaSum(n));
}
}
// This code is contributed by Anant Agarwal.
Python3
# Python3 program to find sum of
# diagonals of spiral matrix
# function returns sum of diagonals
def spiralDiaSum(n):
if n == 1:
return 1
# as order should be only odd
# we should pass only odd
# integers
return (4 * n*n - 6 * n + 6 +
spiralDiaSum(n-2))
# Driver program
n = 7;
print(spiralDiaSum(n))
# This code is contributed by Anant Agarwal.
C#
// C# program to find sum of
// diagonals of spiral matrix
using System;
class GFG {
// function returns sum of diagonals
static int spiralDiaSum(int n)
{
if (n == 1)
return 1;
// as order should be only odd
// we should pass only odd-integers
return (4 * n * n - 6 * n + 6 +
spiralDiaSum(n - 2));
}
// Driver code
public static void Main (String[] args)
{
int n = 7;
Console.Write(spiralDiaSum(n));
}
}
// This code is contributed by parashar...
PHP
Javascript
输出 :
261