马踏棋盘(非递归)

#include <iostream.h>


struct point
{
int x,y;//马的位置
int dir;//这一次马行走的方向
};


struct stack
{
point p[64];//存储马的位置,方便回溯
};
int board [8][8];
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 main()
{
int i,j;
int top=0;
int z;
cout<<"请输入马的初始位置";
cin>>i;
cin>>j;
stack sta;
sta.p[top].x=i;
sta.p[top].y=j;
board [i][j]=top;
chech [i][j]=true;
int nx;
int ny;


for(int u=0;u<64;u++)
sta.p[u].dir=0;//把每个结点的dir清零
for(z=0;;)
{

if(sta.p[top].x+Htry1[z]>=0&&sta.p[top].x+Htry1[z]<8&&
sta.p[top].y+Htry2[z]>=0&&sta.p[top].y+Htry2[z]<8&&
!chech [sta.p[top].x+Htry1[z]][sta.p[top].y+Htry2[z]]//检查要走的下个位置是否可行
)
{
nx=sta.p[top].x+Htry1[z];
ny=sta.p[top].y+Htry2[z];
sta.p[top].dir=z;
top++;
sta.p[top].x=nx;
sta.p[top].y=ny;
board [nx][ny]=top;
chech [nx][ny]=true;
z=-1;
}
else if(z==7)//如果不可行,而且是最好一次检查
{ chech [sta.p[top].x][sta.p[top].y]=false;
top--;
while(1)
{
z=sta.p[top].dir;
if(z!=7)
break;
else
{ chech [sta.p[top].x][sta.p[top].y]=false;
top--;
}
}
}
if(top==-1||top==63)break;//如果回溯到-1,或者栈满,则退出循环
z++;


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

 

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值