#include<stdio.h>
int chess[12][12]={0};
int cnt = 0;
int countChess = 0;
int move[8][2]={{1,-2},{2,-1},{2,1},{1,2},{-1,2},{-2,1},{-2,-1},{-1,-2}};
int initChess();
void printChess();
void horse(int x, int y);
struct Node{
int x;
int y;
int i;
}chessStep[64];
int top = -1;
int main(void){
initChess();
int i,j;
for(i=2; i<10; i++){
for(j=2; j<10; j++){
cnt = 1;
chess[i][j] = cnt;
horse(i,j);
}
}
}
void horse(int x, int y){
int i = 0;
while(cnt < 64){
int row;
int col;
for(i; i<8; i++){
row = x + move[i][0];
col = y + move[i][1];
if(chess[row][col] == 0){
break;
}
}
if(i != 8){
chess[row][col] = ++cnt;
chessStep[++top].x = x;
chessStep[top].y = y;
chessStep[top].i = i;
if(cnt == 64){
printChess();
chess[row][col] = 0;
i = chessStep[top].i + 1;
x = chessStep[top].x;
y = chessStep[top].y;
top--;
cnt--;
}else{
x = row;
y = col;
i = 0;
}
}else{
chess[x][y] = 0;
i = chessStep[top].i + 1;
x = chessStep[top].x;
y = chessStep[top].y;
top--;
cnt--;
}
if(top == -1){
break;
}
}
}
int initChess(){
int i,j;
for(i=0; i<12; ++i){
for(j=0; j<12; ++j){
if(i<2 || i>9 || j<2 || j>9){
chess[i][j]=-1;
}
}
}
}
void printChess(){
++countChess;
printf("第%d个解是:\n", countChess);
int i,j;
for(i=2; i<10; ++i){
for(j=2; j<10; ++j){
printf("%2d ",chess[i][j]);
}
printf("\n");
}
}
|