跳马问题-回溯

 1 //
 2 // Created by snnnow on 2020/5/5.
 3 //
 4 
 5 /*
 6  * 马从横5条线,纵9条线的棋盘左下角往右上角跳(中国象棋)
 7  * 问所有路径?
 8  */
 9 //
10 //很明显是 dfs 呀
11 
12 
13 #include <bits/stdc++.h>
14 using namespace std;
15 int a[100][3];
16 int t=0;
17 int x[4]={2,1,-1,-2};
18 int y[4]={1,2,2,1};
19 int search(int);
20 int print(int);
21 int main(){
22     a[1][1]=0;
23     a[1][2]=0;
24     search(2);
25 
26 }
27 int search(int q){
28     for (int i = 0; i < 4; ++i) {
29         if(a[q-1][1]+x[i]>=0 && a[q-1][2]+y[i]>=0 && a[q-1][1]+x[i]<=8 && a[q-1][2]+y[i]<=8){//判断按照第i种走法是否会越界
30             a[q][1]=a[q-1][1]+x[i];
31             a[q][2]=a[q-1][2]+y[i];
32             if(a[q][1]==4 && a[q][2]==8)
33                 print(q);
34             else
35                 search(q+1);//这个地方没有必要回溯啊,因为新来的值会把原来的值覆盖掉
36         }
37 
38     }
39 }
40 int print(int q){
41     t++;
42     cout<<t<<endl;
43     for (int i = 1; i <= q ; ++i) {
44         cout<<a[i][1]<<","<<a[i][2]<<endl;
45 
46     }
47     return 0;
48 }
原文地址:https://www.cnblogs.com/zhmlzhml/p/12831482.html