马踏棋盘(递归算法)

#include <iostream.h>
int board [8][8]={0};
int Htry1[8]={-2,-1,1,2,2,1,-1,-2};
int Htry2[8]={1,2,2,1,-1,-2,-2,-1};
bool chech[8][8]={0};//标记位置是否已经被占用
int n=1;//就算已走的步数


void findway(int i,int j)
{
for(int z=0;z<8;z++)
{
if(i+Htry1[z]>=0&&i+Htry1[z]<8&&
j+Htry2[z]>=0&&j+Htry2[z]<8&&
!chech [i+Htry1[z]][j+Htry2[z]]//检查要走的下个位置是否可行
)
{

n++;
board[i+Htry1[z]][j+Htry2[z]]=n;
chech[i+Htry1[z]][j+Htry2[z]]=true;
if(n==64||n==-1)goto next;
findway(i+Htry1[z],j+Htry2[z]);
if(n==64||n==-1)goto next;
}
}
n--;
board[i][j]=0;
chech[i][j]=false;




next:return ;
}


int main()
{
int i,j;


int z,y;
cout<<"请输入马的初始位置";
cin>>i;
cin>>j;
chech[i][j]=true;
board[i][j]=1;


findway(i,j);
for(z=0;z<8;z++)
{
for(y=0;y<8;y++)
cout<<board [z][y]<<"";
cout<<endl;
}
return 1;
}

 

posted @ 2011-11-07 21:56  ☆A希亿  阅读(748)  评论(0编辑  收藏  举报