• 中国象棋马走日(要求打印每一种走法) — 递归


     1 //在半个中国象棋棋盘上,马在左下角(1,1)处,马走日字,
     2 //而且只能往右走...不能向左...可上可下...求从起点到(m, n)处有
     3 //几种不同的走法(函数的递归调用)
     4 //要求打印出每一种走法
     5 
     6 
     7 #include<stdio.h>
     8 #include<stdlib.h>
     9 
    10 int counter = 0;
    11 //一个点的结构
    12 typedef struct Point
    13 {
    14     int x;
    15     int y;
    16 }Point;
    17 
    18 //定义一个结构体保存路径
    19 typedef struct Step
    20 {
    21     int num;
    22     Point steps[9];
    23 }Step;
    24 //声明一个路径结构体全局变量,并初始化
    25 Step trace = {-1,{1,1}};
    26 
    27 
    28 //声明函数
    29 void print();
    30 int horse(int x1,int y1,int x2,int y2);
    31 
    32 int main()
    33 {
    34     char ch;
    35     while(ch != EOF)
    36     {
    37         int m,n;
    38         counter = 0;
    39         printf("请输入目的地址,用英文逗号隔开,如2,3:
    ");
    40         if(scanf("%d,%d",&m,&n) < 2)
    41             printf("输入有不全,请重新输入!
    ");
    42         else if(m>9||m<1||n>5||n<1)
    43                 printf("输入有误,请重新输入!
    ");
    44             else
    45                 printf("共有%d种走法
    ",horse(1,1,m,n));
    46         printf("
    输入ctrl+z退出,任意键继续
    ");
    47         getchar();
    48         ch = getchar();
    49         system("cls");
    50     }
    51     return 0;
    52 }
    53 
    54 int horse(int x1,int y1,int x2,int y2)
    55 {
    56     int result = 0;
    57     //创建并添加该点
    58     Point po = {x1,y1};
    59     trace.steps[++trace.num] = po;
    60     if(x2 < x1  || (x1==x2 && y1 != y2))
    61     {
    62         trace.num--;    //返回前,去除该点
    63         return 0;
    64     }
    65     
    66     if(x1 == x2 && y1 == y2)
    67     {
    68         counter++;
    69         print();
    70         trace.num--;    //返回前,去除该点
    71         return 1;
    72     }
    73     
    74     if(x1+1 <= 9 && y1+2 <= 5)
    75         result+=horse(x1+1,y1+2,x2,y2);
    76     if(x1+1 <= 9 && y1-2 >0)
    77         result+=horse(x1+1,y1-2,x2,y2);
    78     if(x1+2 <= 9 && y1+1 <= 5)
    79         result+=horse(x1+2,y1+1,x2,y2);
    80     if(x1+2 <= 9 && y1-1 > 0)
    81         result+=horse(x1+2,y1-1,x2,y2);
    82 
    83     trace.num--;        //返回前,去除该点
    84     return result;
    85 }
    86 
    87 void print()
    88 {
    89     int i;
    90     printf("第%d种走法为:",counter);
    91     for(i = 0;i <= trace.num;i++)
    92     {
    93         printf("[%d,%d] ",trace.steps[i].x,trace.steps[i].y);
    94     }
    95     printf("
    ");
    96 }
  • 相关阅读:
    用到的一些方法
    Android屏蔽Home键
    Android自定义GridView显示一行,并且可以左右滑动
    模糊匹配字母大小写
    Android四大组件之Content Provider的学习
    用于小数据存储的SharedPreferences
    Android小知识点
    【译】用C/C++操作链表
    和好友的QQ记录,多关注哈需要关怀的人
    岁不待人_20080321
  • 原文地址:https://www.cnblogs.com/houjun/p/6507691.html
Copyright © 2020-2023  润新知