马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
#include <stdio.h>
#include <time.h>
#define X 8
#define Y 8
int chess[X][Y];
// 判断下一步可不可走,可走则走,不可走则返回0
int nextxy(int *x, int *y, int count) //count 0~7表示八个方位
{
switch(count)
{
case 0:
if( *x+2<=X-1 && *y-1>=0 && chess[*x+2][*y-1]==0 )
{
*x = *x + 2;
*y = *y - 1;
return 1;
}
break;
case 1:
if( *x+2<=X-1 && *y+1<=Y-1 && chess[*x+2][*y+1]==0 )
{
*x = *x + 2;
*y = *y + 1;
return 1;
}
break;
case 2:
if( *x+1<=X-1 && *y-2>=0 && chess[*x+1][*y-2]==0 )
{
*x = *x + 1;
*y = *y - 2;
return 1;
}
break;
case 3:
if( *x+1<=X-1 && *y+2<=Y-1 && chess[*x+1][*y+2]==0 )
{
*x = *x + 1;
*y = *y + 2;
return 1;
}
break;
case 4:
if( *x-2>=0 && *y-1>=0 && chess[*x-2][*y-1]==0 )
{
*x = *x - 2;
*y = *y - 1;
return 1;
}
break;
case 5:
if( *x-2>=0 && *y+1<=Y-1 && chess[*x-2][*y+1]==0 )
{
*x = *x - 2;
*y = *y + 1;
return 1;
}
break;
case 6:
if( *x-1>=0 && *y-2>=0 && chess[*x-1][*y-2]==0 )
{
*x = *x - 1;
*y = *y - 2;
return 1;
}
break;
case 7:
if( *x-1>=0 && *y+2<=Y-1 && chess[*x-1][*y+2]==0 )
{
*x = *x - 1;
*y = *y + 2;
return 1;
}
break;
default:
break;
}
return 0;
}
void print()
{
int i, j;
for ( i=0; i < X; i++ )
{
for ( j=0; j < Y; j++ )
{
printf("%2d\t", chess[i][j]);
}
printf("\n");
}
printf("\n");
}
//走过一步,tag就加1
int TravelChessBoard(int x, int y, int tag)
{
int x1=x, y1=y, flag=0, count=0; //x1,y1表示一下个位置,x,y表示当前位置,我们这里用了递归,所以x,y是变化的
chess[x][y] = tag;
// 如果全部位置走遍,则打印棋盘
if( tag == X*Y )
{
print();
return 1; //返回给主函数
}
flag = nextxy(&x1, &y1, count);
while( 0==flag && count < 7 ) //如果初始位置在右上角(只是假设),count=0表示初始位置的右上角的位置,则case 0不可走,直接到了defult,跳出返回0,即flag等于0,然后看初始位置的其他方位是否可行
{
count++;
flag = nextxy(&x1, &y1, count);
}
while( flag ) //flag为1,表示可走为0表示不可走
{
if( TravelChessBoard(x1, y1, tag+1) )
{
return 1;
}
x1 = x; //如果走到左下角而且它的右上角的两个方位都走过,则回溯选择当前位置的其他方位
y1 = y;
count++;
flag = nextxy(&x1, &y1, count);
while( 0==flag && count < 7 )
{
count++;
flag = nextxy(&x1, &y1, count);
}
}
//
if( 0 == flag )
{
chess[x][y] = 0;
}
return 0;
}
int main()
{
int i, j;
clock_t start, finish;
start = clock();
for ( i=0; i < X; i++ )
{
for ( j=0; j < Y; j++ )
{
chess[i][j] = 0;
}
}
if( !TravelChessBoard(2, 0, 1) )
{
printf("马踏棋盘失败~\n");
}
finish = clock();
printf("总共耗时%f秒\n\n", (double)(finish-start)/CLOCKS_PER_SEC);
return 0;
}
|