C++实现马踏棋盘(骑士周游)
更新时间:2022年02月15日 11:41:10 作者:lld951027
这篇文章主要为大家详细介绍了C++实现马踏棋盘,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
马踏棋盘,用1枚马走遍棋盘。我用一个二维数组记录模拟的整个路径,x为列,y为行,以顺时针的方式寻找下一格,算法比较简单,就通过递归和循环回溯即可,就是如果是8*8的数组,最坏可能执行8^(x*y)次,耗时长到怀疑人生。
#include<iostream> #define X 5 #define Y 5 void ShowResult(); using namespace std; int chess[Y][X]={ 0 }; int counter=0; int Next(int* x,int* y,int where){ switch(where){ case 0: if(*x+1<X&&*y-2>=0&&chess[*y-2][*x+1]==0){ *x+=1; *y-=2; return 1; } break; case 1: if(*x+2<X&&*y-1>=0&&chess[*y-1][*x+2]==0){ *x+=2; *y-=1; return 1; } break; case 2: if(*x+2<X&&*y+1<Y&&chess[*y+1][*x+2]==0){ *x+=2; *y+=1; return 1; } break; case 3: if(*x+1<X&&*y+2<Y&&chess[*y+2][*x+1]==0){ *x+=1; *y+=2; return 1; } break; case 4: if(*x-1>=0&&*y+2<Y&&chess[*y+2][*x-1]==0){ *x-=1; *y+=2; return 1; } break; case 5: if(*x-2>=0&&*y+1<Y&&chess[*y+1][*x-2]==0){ *x-=2; *y+=1; return 1; } break; case 6: if(*x-2>=0&&*y-1>=0&&chess[*y-1][*x-2]==0){ *x-=2; *y-=1; return 1; } break; case 7: if(*x-1>=0&&*y-2>=0&&chess[*y-2][*x-1]==0){ *x-=1; *y-=2; return 1; } break; } return 0; } int Explore(int x,int y){ int x1=x; int y1=y; int flag; int where=0; counter++; chess[y][x]=counter; if(counter==X*Y){ return 1; } flag=Next(&x1,&y1,where); while(flag==0&&where<7){ where++; flag=Next(&x1,&y1,where); } while(flag){ if(Explore(x1,y1)==1){ return 1; } 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--; } return 0; } void ShowResult(){ for(int i=0;i<Y;i++){ for(int j=0;j<X;j++){ cout.width(4); cout<<chess[i][j]<<' '; } cout<<endl; } cout<<endl; } int main(){ int start=clock(); int result=Explore(2,1); int end=clock(); if(result){ ShowResult(); } else{ cout<<"have no path!"<<endl; } cout<<"spend time:"<<(end-start)/CLOCKS_PER_SEC<<" s"<<endl; return 0; }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
相关文章
C++实现LeetCode(170.两数之和之三 - 数据结构设计)
这篇文章主要介绍了C++实现LeetCode(170.两数之和之三 - 数据结构设计),本篇文章通过简要的案例,讲解了该项技术的了解与使用,以下就是详细内容,需要的朋友可以参考下2021-08-08C++编译报错:||error: ld returned 1 exit 
这篇文章主要介绍了C++编译报错:||error: ld returned 1 exit status|的解决方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教2024-01-01MongoDB C 驱动程序安装(libmongoc) 和 BSON 库(libbson)方法
这篇文章主要介绍了安装 MongoDB C 驱动程序 (libmongoc) 和 BSON 库 (libbson),本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下2022-09-09
最新评论