主题:数据结构(C语言版)魔阵
wangjixue
[专家分:0] 发布于 2007-09-08 10:38:00
n阶魔阵问题:给定一奇数n,构造一个n阶魔阵。n阶魔阵是一个n阶方阵,其元素由自然数1,2,3,...,n2组成.魔阵的每行元素之和、每列元素之和以及主、副对角线元素之和均相等。即对于给定的奇整数n以及i=1,2,3,...,n,魔阵a满足条件:
ai1+ai2+...+ain=a1i+a2i+...+ani=a11+a22+...+ann=a1,n-1+1+a2,n-2+1+...+an,n-n+1
回复列表 (共1个回复)
沙发
lv5329545 [专家分:20] 发布于 2007-09-21 22:22:00
#include <iostream>
int main()
{
using namespace std;
cout << "请输入N * N的N值(奇数): ";
int n, i, j;
cin >> n;
while (n <= 0 || n % 2 == 0)
{
cout << "N值错误!\n";
cout << "请输入N * N的N值(奇数): ";
cin >> n;
}
int** a = new int*[n];
for (i = 0; i < n; i++)
a[i] = new int[n];
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
a[i][j] = 0;
i = 0;
int row = 0, col = n / 2;
a[row][col] = 1;
while (i < n * n - 1)
{
if (row == 0 && col == n - 1)
{
if (!a[n - 1][0])
{
row = n - 1;
col = 0;
}
else
row++;
}
else if (row == 0)
{
if (!a[n - 1][col + 1])
{
row = n - 1;
col++;
}
else
row++;
}
else if (col == n - 1)
{
if (!a[row - 1][0])
{
row--;
col = 0;
}
else
row++;
}
else
{
if (a[row - 1][col + 1])
row++;
else
{
row--;
col++;
}
}
a[row][col] = i + 2;
i++;
}
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
cout << a[i][j];
if (a[i][j] / 10)
cout << ' ';
else
cout << " ";
}
cout << endl;
}
for (i = 0; i < n; i++)
delete [] a[i];
delete [] a;
return 0;
}
我来回复