回溯5--马的遍历
回溯5--马的遍历
一、心得
二、题目及分析
三、代码及结果
1 /* 2 马的遍历 3 不用回头 4 5 */ 6 #include <iostream> 7 using namespace std; 8 9 int ans[100][2]; 10 int total=0; 11 12 bool vis[100][100]; 13 //row colum 14 int horseRoad[5][2]={{0,0},{2,1},{1,2},{-1,2},{-2,1}}; 15 16 void print(int k){ 17 total++; 18 cout<<total<<": "<<endl; 19 cout<<"("<<0<<","<<0<<")"<<" "; 20 for(int i=1;i<=k;i++){ 21 cout<<"("<<ans[i][0]<<","<<ans[i][1]<<")"<<" "; 22 } 23 cout<<endl; 24 } 25 26 void search(int r,int c,int k){ 27 if(vis[4][8]==1) print(k-1); 28 else 29 for(int i=1;i<=4;i++){ 30 int r1=r+horseRoad[i][0]; 31 int c1=c+horseRoad[i][1]; 32 if(r1>=0&&r1<=4&&c1>=0&&c1<=8){ 33 ans[k][0]=r1; 34 ans[k][1]=c1; 35 vis[r1][c1]=1; 36 search(r1,c1,k+1); 37 vis[r1][c1]=0; 38 } 39 } 40 41 } 42 43 int main(){ 44 search(0,0,1); 45 cout<<total<<endl; 46 return 0; 47 }
版权申明:欢迎转载,但请注明出处
一些博文中有一些参考内容因时间久远找不到来源了没有注明,如果侵权请联系我删除。
在校每年国奖、专业第一,加拿大留学,先后工作于华东师范大学和香港教育大学。
2024-09-05:27岁,宅加太忙,特此在网上找女朋友,vx:fan404006308
AI交流资料群:753014672