魔方构造问题
一个魔方(magic square)就是由1到n平方的整数构成的n*n矩阵,其中每行每列以及主对角线上的数字之和都相等。
当n为奇数时,Coxeter法则可以产生魔方:
把1放入第一行最中间的方格中。向左上方移动,并按照数字的递增顺序,把数字填入空方格。如果移出了魔方(即越过了魔方边界),则进入魔方对边的对应放歌。继续填写方格。如果一个方格已被填入数字,则向下继续填写。
魔方程序涉及到的Coxeter法则属于群论。
魔方程序迭代写法:
/*魔方程序-迭代*/
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 15 /* maximum size of square */
void main(){
/* construct a magic square, iteratively */
static int square[MAX_SIZE][MAX_SIZE];
int i, j, row, column; /* indices */
int count; /* counter */
int size;
printf("Enter the size of square: ");
scanf("%d", &size);
/* check for input errors */
if(size < 1 || size > MAX_SIZE + 1){
fprintf(stderr, "Error! Size is out of range\n");
exit(1);
}
if(!(size % 2)){
fprintf(stderr, "Error! Size is even\n");
exit(1);
}
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 and j are current position */
i = 0;
j = (size-1) / 2;
for(count = 2; count <= size*size; count++){
row
}
}
魔方程序递归写法:
/*魔方程序-递归*/
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 15 /* maximum size of square */
void checkInput(int size){
/* check for input errors */
if(size < 1 || size > MAX_SIZE + 1){
fprintf(stderr, "Error! Size is out of range\n");
exit(1);
}
if(!(size % 2)){
fprintf(stderr, "Error! Size is even\n");
exit(1);
}
}
void initSquare(int size, int sq[][MAX_SIZE]){
int i,j;
for(i = 0; i < size; i++)
for(j = 0; j < size; j++)
sq[i][j] = 0;
}
void magicSquare(int i, int j, int n, int size, int sq[][MAX_SIZE]){
if(n == size*size){
sq[i][j] = n;
}
else{
sq[i][j] = n;
i = (i-1 < 0) ? (size - 1):(i - 1);
j = (j-1 < 0) ? (size - 1):(j - 1);
if(sq[i][j]){
i = (i+2) % size;
j = (j+1) % size;
}
magicSquare(i,j,n+1,size,sq);
}
}
void output(int size, int sq[][MAX_SIZE]){
int i,j;
printf(" Magic Square of size %d: \n\n", size);
for(i = 0; i < size; i++){
for(j = 0; j < size; j++)
printf("%5d", sq[i][j]);
printf("\n");
}
printf("\n\n");
}
void main(){
static int square[MAX_SIZE][MAX_SIZE];
int i, j;
int size;
printf("Enter the size of square: ");
scanf("%d", &size);
checkInput(size);
/* init the magic square */
initSquare(size, square);
i = 0;
j = (size-1) / 2;
magicSquare(i,j,1,size,square);
/* output the magic square */
output(size, square);
}