回溯8--跳马问题

回溯8--跳马问题

一、心得

二、题目及分析

三、代码及结果

 1 /*
 2 一边默认一个顺序,另外一边出要求
 3 选书:默认按照人一个个来,选书的话就一本本选就好了 
 4 */ 
 5 #include <iostream>
 6 using namespace std;
 7 
 8 //标志数组
 9 int vis[6][6];
10 //结果数组
11 int ans[6][6]; 
12 int horseRoad[9][2]={{0,0},{2,1},{1,2},{-1,2},{-2,1},{-2,-1},{-1,-2},{1,-2},{2,-1}};
13 int total=0;
14 
15 void print(){
16     total++;
17     if(total<=5){
18         cout<<"<"<<total<<">"<<": "<<endl;
19         for(int i=0;i<=4;i++){
20             for(int j=0;j<=4;j++){
21                 printf("%2d ",ans[i][j]);
22             }
23             cout<<endl;
24         }
25     }    
26 }
27 
28 int search(int r,int c,int step){
29     if(step==26) print();
30     else
31         for(int i=1;i<=8;i++){
32             int r1=r+horseRoad[i][0];
33             int c1=c+horseRoad[i][1];
34             if(!vis[r1][c1]&&r1>=0&&r1<=4&&c1>=0&&c1<=4){
35                 ans[r1][c1]=step,vis[r1][c1]=1;
36                 search(r1,c1,step+1);
37                 vis[r1][c1]=0;
38             }
39         }
40 } 
41 
42 int main(){
43     ans[0][0]=1;
44     vis[0][0]=1;
45     search(0,0,2);
46     cout<<total;
47     return 0;
48 } 

原文地址:https://www.cnblogs.com/Renyi-Fan/p/7124380.html