Ka的回溯编程练习 Part3|马的遍历

 1 #include <stdio.h>
 2 int board[100][3]={0},totally=0;
 3 int x[4]={2,1,-1,-2},y[4]={1,2,2,1};
 4 void o(int k) //这个输出函数需要借助回溯中n的值来完成输出 
 5 {
 6     totally++;
 7     printf("%d:",totally);
 8     int r;
 9     for(r=1;r<=k-1;r++)
10         printf("|%d,%d|->",board[r][1],board[r][2]);
11     printf("|4,8|
"); //最后一个另外输出 
12 }
13 int search(int n)
14 {
15     int i;
16     for(i=0;i<=3;i++)
17     {
18         if(board[n-1][1]+x[i]<=4&&  //之前的坐标进行该种跳跃不会越界的话
19            board[n-1][1]+x[i]>=0&&
20            board[n-1][2]+y[i]>=0&&
21            board[n-1][2]+y[i]<=8)
22           {
23                board[n][1]=board[n-1][1]+x[i];
24                board[n][2]=board[n-1][2]+y[i];
25                if(board[n][1]==4&&board[n][2]==8) o(n);
26                else search(n+1);//不必担心对n没有限制,因为n如果太大会因为越界不发进入此if 
27                //因为下一次操作会重置board,不必再重新调回0。 
28            }
29     }
30 }
31 int main()
32 {
33     search(2);  //第一个点的坐标已经通过初始化确定为0.0,则从第二个点开始寻找
34     return 0;
35 }

看注释啦啦啦

原文地址:https://www.cnblogs.com/KakagouLT/p/4515136.html