//*****************************
//* 程 序 名:Jump1.cpp *
//* 作 者:my *
//* 编制时间:2013年9月23日 *
//* 主要功能:跳马 *
//*****************************
#include <iomanip.h> // 预编译命令
int N; // 棋盘大小
int **Field = NULL; //棋盘
void Output() //输出
{
int i,j;
for(i=0;i<N;i++)
{
for(j=0;j<N;j++)
cout<<setw(5)<<Field[i][j];
cout<<endl;
}
}
//Function name :TryJump
//Description :用回溯法搜索可能的移动路径
//Return type :bool 表示是否搜索成功
//Argument :int x 当前要尝试的x位置
//Argument :int y 当前要尝试的y位置
//Argument :int step 表示当前是第几步
bool TryJump(int x,int y,int step)
{
if(x<0||x>N-1||y<0||y>N-1) //判断所走的位置是否在棋盘上
return false;
else
{
if(Field[x][y]!=0) // 当前尝试的格子已经走过
return false;
Field[x][y] = step; // 走入这一格
if(step == N * N) // 是否已走完所有格子(判断语句,不应该用赋值语句:=,应该用等于:==)
return true;
if( ! TryJump(x-1,y-2,step+1)&& //尝试下一步(因为这里有x y的加减法,所以应该在开始就判断x y的值是否为负数或超出棋盘)
! TryJump(x-1,y+2,step+1)&&
! TryJump(x+1,y-2,step+1)&&
! TryJump(x+1,y+2,step+1)&&
! TryJump(x-2,y-1,step+1)&&
! TryJump(x-2,y+1,step+1)&&
! TryJump(x+2,y-1,step+1)&&
! TryJump(x+2,y+1,step+1))
{
Field[x][y] = 0; //失败,回溯
return false;
}
else
return true;
}
}
void main() //主函数
{
cout<<"请输入跳马棋盘的大小(N*N)N=";
cin>>N; //得到棋盘大小
int x,y;
cout<<"请输入马的初始位置(0<=x,y<="<<N-1<<")\n";
cout<<"x="; //得到初始位置
cin>>x;
cout<<"y=";
cin>>y;
Field = new int *[N]; //构造棋盘
int i,j;
for(i=0;i<N;i++)
{
Field[i] = new int[N];
for(j=0;j<N;j++)
Field[i][j] = 0;
}
if(TryJump(x,y,1)) //尝试移动
Output();
else
cout<<"无解\n";
}
跳马程序的调试
最新推荐文章于 2023-09-11 21:37:53 发布