zoukankan      html  css  js  c++  java
  • 中国象棋马走日 — 递归

     1 //在半个中国象棋棋盘上,马在左下角(11)处,马走日字,
     2 //而且只能往右走...不能向左...可上可下...求从起点到(m, n)处有
     3 //几种不同的走法(函数的递归调用)
     4 
     5 #include<stdio.h>
     6 #include<stdlib.h>
     7 
     8 int horse(int x1,int y1,int x2,int y2);
     9 int main()
    10 {
    11     char ch;
    12     while(ch != EOF)
    13     {
    14         int m,n;
    15         printf("请输入目的地址,用英文逗号隔开,如2,3:
    ");
    16         if(scanf("%d,%d",&m,&n) < 2)
    17             printf("输入有不全,请重新输入!
    ");
    18         else if(m>9||m<1||n>5||n<1)
    19                 printf("输入有误,请重新输入!
    ");
    20             else
    21                 printf("结果为:%d",horse(1,1,m,n));
    22         printf("
    输入ctrl+z退出,任意键继续
    ");
    23         getchar();
    24         ch = getchar();
    25         system("cls");
    26     }
    27     return 0;
    28 }
    29 
    30 //走马的实现
    31 int horse(int x1,int y1,int x2,int y2)
    32 {
    33     //在这个算法中,目的地不变,在变的一直是起点,递归有两个出口,一个返回0(表示找不到),一个返回1(表示找到)。
    34     int result = 0;
    35     if( x1 > x2 || x1==x2 && y1 != y2)     //x1 > x2 表示已经往左边走,
    36         return 0;                        //x1==x2 && y1 != y2 表示已在同一竖线上,但横线不重合,注定走不到一起。
    37     else if(x1==x2 && y1==y2)
    38         return 1;
    39     else
    40     {
    41         //每一个点有“四种”走法,每一个起点都递归调用。
    42         //注意到x1只能 + ,因为只能往右走。
    43         if(x1+2<=9 && y1+1<=5)
    44             result += horse(x1+2,y1+1,x2,y2);
    45         if(x1+1<=9 && y1+2<=5)
    46             result += horse(x1+1,y1+2,x2,y2);
    47         if(x1+2<=9 && y1-1>=1)
    48             result += horse(x1+2,y1-1,x2,y2);
    49         if(x1+1<=9 && y1-2>=1)
    50             result += horse(x1+1,y1-2,x2,y2);
    51         //所有递归调用回溯之后,得到一个总的result,即步数。
    52         return result;
    53     }
    54 }
  • 相关阅读:
    java面向对象高级分层实例_实体类
    But what exactly do we mean by "gets closer to"?
    information entropy as a measure of the uncertainty in a message while essentially inventing the field of information theory
    SVM vs. Softmax
    every row of W is a classifier for one of the classes
    Hinge Loss
    polynomial time
    Conditional random fields
    Frobenius Norm
    L2 范数 L1 范数 出租车范数
  • 原文地址:https://www.cnblogs.com/houjun/p/6507692.html
Copyright © 2011-2022 走看看