前言
所谓的n阶幻方是指一个 N x N 的方阵,方阵的每行、每列和两条对角线上元素的和都相等。
有奇数阶幻方、双偶数(4m)阶幻方和单偶数(4m + 2)阶幻方。
一、奇数阶幻方
#include <stdio.h>
#include <stdlib.h> // malloc
#include <string.h> // memset
int* Magic(int n)
{
int nX = 0;
int nY = 0;
int i = 0;
// pMagic[n][n] &pMagic[x][y] = (int)pMagic + sizeof(int)*(x*n + y)
int* pMagic = (int*)malloc(sizeof(int) * n * n);
if (pMagic == NULL)
{
return NULL;
}
memset(pMagic, 0, sizeof(int) * n * n);
// 填充 pMagic[n/2][n-1]=1 方针中中间一行的最右边
nX = n / 2;
nY = n - 1;
pMagic[nX * n + nY] = 1;
// 填充n*n个数,每次填充的数正好为i
for (i = 2; i <= n * n; i++)
{
// 从矩阵的角度看,如果“右下角”没有填充过数值,则填充“右下角”
if (pMagic[((nX + 1) % n) * n + ((nY + 1) % n)] == 0)
{
nX = (nX + 1) % n;
nY = (nY + 1) % n;
pMagic[nX * n + nY] = i;
}
else
{
// 如果“右下角”填充了数值,则填充在左边
nX = nX % n;
nY = (nY - 1) % n;
pMagic[nX * n + nY] = i;
}
}
return pMagic;
}
void ShowMagic(int* pMagic, int n)
{
int i = 0;
int j = 0;
int nRowSum = 0;
for (i = 0; i < n; i++)
{
nRowSum = 0;
// 打印每一列
for (j = 0; j < n; j++)
{
nRowSum = nRowSum + pMagic[i * n + j];
printf("%-4d\t", pMagic[i * n + j]);
}
printf("nRowSum=%04d", nRowSum);
printf("\r\n\r\n");
}
}
int main()
{
int n = 0;
int* pMagic = NULL;
while (1)
{
printf("please input the number(-1 to exit):\r\n");
scanf("%d", &n);
if (n == -1)
{
break;
}
pMagic = Magic(n);
if (pMagic != NULL)
{
ShowMagic(pMagic, n);
}
system("pause");
if (pMagic != NULL)
{
free(pMagic);
pMagic = NULL;
}
}
system("pause");
return 0;
}