/************************************************************************
9宫格排版, 把1..9分别放到9个格子中,不能重复,横竖相加都相等
************************************************************************/
#include <stdio.h>
#include <stdlib.h>
//宏定义 N*N 空格
#define N 3
int main()
{
int nX, nY, nTempX, nTempY, i, j, nRowSum, nColSum;
char aryMap[N][N] = {0};
/*确定起始位置,最下一行的正中间*/
nX = N-1;
nY = (N-1) / 2;
aryMap[nX][nY] = 1;
for (i = 2; i <= N*N; i++)
{
//确定下一格的位置,当前格的右下角
nTempX = nX + 1;
nTempY = nY - 1;
if (nTempX > N-1)
{
nTempX = 0;
}
if (nTempY < 0)
{
nTempY = N - 1;
}
//如果还没写值就直接写入
if (0 == aryMap[nTempX][nTempY])
{
aryMap[nTempX][nTempY] = i;
}
//否则就写到头顶
else
{
nTempX = nX - 1;
nTempY = nY;
aryMap[nTempX][nTempY] = i;
}
nX = nTempX;
nY = nTempY;
}
//显示出来
for (i = 0; i < N; i++)
{
for (j = 0; j < N; j++)
{
printf("%d\t", aryMap[i][j]);;
}
printf("\r\n\r\n");
}
for (i = 0; i < N; i++)
{
nRowSum = 0;
nColSum = 0;
for (j = 0; j < N; j++)
{
nColSum = nColSum + aryMap[i][j];
nRowSum = nRowSum + aryMap[j][i];
}
printf("%d, %d\r\n", nColSum, nRowSum);
}
return 0;
}