#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
srand( time(NULL) );
int board[8][8];
int accessibility[8][8]={
2,3,4,4,4,4,3,2,
3,4,6,6,6,6,4,3,
4,6,8,8,8,8,6,4,
4,6,8,8,8,8,6,4,
4,6,8,8,8,8,6,4,
4,6,8,8,8,8,6,4,
3,4,6,6,6,6,4,3,
2,3,4,4,4,4,3,2};
memset( board, 0, sizeof(board) );//全部初始化为0
int currentRow=0;
int currentColumn=0;//从左上角开始
int horizontal[8]={2,1,-1,-2,-2,-1,1,2};
int vertical[8]={-1,-2,-2,-1,1,2,2,1};
int count=0;
int moveNumber=0;
int StartRow=currentRow;//起点行
int StartColumn=currentColumn;//起点列
int testRow=0;//测试行
int testColumn=0;//测试列
int priorRow=0;//优先访问行
int priorColumn=0;//优先访问列
int sequence[8];//用随机数产生的移动类型序列
int i=0,j=0;
int minimum;
while ( 1 )
{
minimum=8;
sequence[0]=rand()%8;
i=1;
while ( i<8 )
{
sequence[i]=rand()%8;
for ( j=0; j<i; ++j )
if ( sequence[j] == sequence[i] )
break;
if ( j == i)
++i;
}
StartRow=currentRow;
StartColumn=currentColumn;
for ( i=0; i<8; ++i )
{
moveNumber=sequence[i];
testRow=currentRow+vertical[moveNumber];
testColumn=currentColumn+horizontal[moveNumber];
if ( board[testRow][testColumn] == 0 && testRow>=0
&& testRow<=7 && testColumn>=0 && testColumn<=7 )//终点符合要求
{
if ( accessibility[testRow][testColumn] <= minimum )
{
minimum=accessibility[testRow][testColumn];
priorRow=testRow;
priorColumn=testColumn;
}
}
}
currentRow=priorRow;//马移动到优先访问点上
currentColumn=priorColumn;
if ( currentRow == StartRow && currentColumn == StartColumn )//马未移动
break;
else
{
++count;
board[currentRow][currentColumn]=count;
continue;
}
}
for ( i=0; i<8; ++i )//打印棋盘
{
for ( j=0; j<8; ++j )
printf( "%d/t", board[i][j] );
printf( "/n" );
}
printf( "The horse goes %d steps./n", count );
return 0;
}