如何使用C++实现马踏棋盘(C++,开发技术)

时间:2024-05-09 07:25:28 作者 : 石家庄SEO 分类 : 开发技术
  • TAG :

马踏棋盘,用1枚马走遍棋盘。我用一个二维数组记录模拟的整个路径,x为列,y为行,以顺时针的方式寻找下一格,算法比较简单,就通过递归和循环回溯即可,就是如果是8*8的数组,最坏可能执行8^(x*y)次,耗时长到怀疑人生。

如何使用C++实现马踏棋盘

#include<iostream>#defineX5#defineY5voidShowResult();usingnamespacestd;intchess[Y][X]={0};intcounter=0;intNext(int*x,int*y,intwhere){switch(where){case0:if(*x+1<X&&*y-2>=0&&chess[*y-2][*x+1]==0){*x+=1;*y-=2;return1;}break;case1:if(*x+2<X&&*y-1>=0&&chess[*y-1][*x+2]==0){*x+=2;*y-=1;return1;}break;case2:if(*x+2<X&&*y+1<Y&&chess[*y+1][*x+2]==0){*x+=2;*y+=1;return1;}break;case3:if(*x+1<X&&*y+2<Y&&chess[*y+2][*x+1]==0){*x+=1;*y+=2;return1;}break;case4:if(*x-1>=0&&*y+2<Y&&chess[*y+2][*x-1]==0){*x-=1;*y+=2;return1;}break;case5:if(*x-2>=0&&*y+1<Y&&chess[*y+1][*x-2]==0){*x-=2;*y+=1;return1;}break;case6:if(*x-2>=0&&*y-1>=0&&chess[*y-1][*x-2]==0){*x-=2;*y-=1;return1;}break;case7:if(*x-1>=0&&*y-2>=0&&chess[*y-2][*x-1]==0){*x-=1;*y-=2;return1;}break;}return0;}intExplore(intx,inty){intx1=x;inty1=y;intflag;intwhere=0;counter++;chess[y][x]=counter;if(counter==X*Y){return1;}flag=Next(&x1,&y1,where);while(flag==0&&where<7){where++;flag=Next(&x1,&y1,where);}while(flag){if(Explore(x1,y1)==1){return1;}else{x1=x;y1=y;where++;flag=Next(&x1,&y1,where);while(flag==0&&where<7){where++;flag=Next(&x1,&y1,where);}}}if(flag==0){chess[y][x]=0;counter--;}return0;}voidShowResult(){for(inti=0;i<Y;i++){for(intj=0;j<X;j++){cout.width(4);cout<<chess[i][j]<<'';}cout<<endl;}cout<<endl;}intmain(){intstart=clock();intresult=Explore(2,1);intend=clock();if(result){ShowResult();}else{cout<<"havenopath!"<<endl;}cout<<"spendtime:"<<(end-start)/CLOCKS_PER_SEC<<"s"<<endl;return0;}
 </div> <div class="zixun-tj-product adv-bottom"></div> </div> </div> <div class="prve-next-news">
本文:如何使用C++实现马踏棋盘的详细内容,希望对您有所帮助,信息来源于网络。
上一篇:Python中结构型组合模式的示例分析下一篇:

7 人围观 / 0 条评论 ↓快速评论↓

(必须)

(必须,保密)

阿狸1 阿狸2 阿狸3 阿狸4 阿狸5 阿狸6 阿狸7 阿狸8 阿狸9 阿狸10 阿狸11 阿狸12 阿狸13 阿狸14 阿狸15 阿狸16 阿狸17 阿狸18