回溯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-10-22 22:16:37