Hello,大家好。今天和大家分享一个趣味数学的魔方问题。相信之前,你们都玩过《某者》或寒暑假作业后面的趣味填数游戏。给你一个某种大小的矩阵(一般都是奇数3x3, 5x5, 7x7...), 每个单元取自然数,简单点的会先给你填好几个数字,要求你填出剩下的空格,使每行、每列,以及两条主对角线的和都相等。

小伙伴们,如果做不出来,看我如何让C语言帮我们快速获得结果。
在开始编程之前,首先了解一下破解此类数独魔方游戏的"葵花宝典"☞Coxeter规则:(PS大家可以结合上图,边看边填!)
开始时,在 魔方第一行的中间一格放 1。然后重复以下步骤:移 动到左上一格,把当前的数加 1放 在这个位置。如果移动时超 出魔方范围,则 想象与当前状态完全相同的另一个魔方,对齐紧靠在超 出的那条边界线上,因 而可以继续。如果移动到的格子 已经放置过数字,则 从这个格子的位置向正下方移动一格。直到把所有格子都放满数字为止!大家做出来了吗?

好,废话不多说。直接看Code
#include
#define MAX_SIZE 15 /* maximum size of square */
void main (void)
{ /*construct a magic square, iterativety */
int square[MAX_SIZE][MAX_SIZE] ;
int i, j, row, col; /* indexes * /
int count; /* counter * /
int size; /* square size * /
printf ( "Enter-the-size-of-the-square: -" ) ;
scanf ("%d" , &size) ;
/* check for input errors */
if (size<1 | | size>MAX_SIZE) {
fprintf (stderr ,"size out of range ") ;
exit (EXIT_FAILURE) ;
}
if (! (size%2)) {
fprintf (stderr, "Error!-Size-is-even " );
exit (EXIT_FAILURE) ;
}
for (i=0; i<size;i++)
for (j=0; j<size; j++) square[i][j] = 0 ;
square[0][(size-1) /2]=1;
/* middle of first row * /
i = 0; j = (size-1) /2;
/* i and j are curent position * /
for (count=2 ; count<=size*size; count++ ) {
row = (i-1<0) ? (size-1) : (i-1) ; /* up * /
col = (j -1<0) ? (size-1) : (j -1) ; /* lef t */
if (square [row] [col] ) i = (++i) % size;
/* down */
else { i = row; j = (j-1<0) ? (size-1) : --j; } /*square r,s unoccupied * /
square[i][j] = count ;
}
/* output the magic square */
printf ( "Magic-square-of-size-%d: " , size) ;
for (i=0; i<size; i++) {
for (j=0; j<size;j++)
printf("%5d ",square[i][j]);
printf(" ");
}
printf(" ");
}
机器测试通过。无图无真相!

