阿九。 发表于 2021-5-9 20:17:06

C语言递归小问题

这答案是如何实现的呢
Steps of moving 3 disks from A to C by means of B:
Move 1: A to C
Move 2: A to B
Move 1: C to B
Move 3: A to C
Move 1: B to A
Move 2: B to C
Move 1: A to C

第一次递归不是 n-1 吗 不是应该输出 Move 2:吗?




//Think Different !!!
/*
    //程序功能:通过递归实现汉诺塔;
*/

#include <stdio.h>

void move(int n, char source, char goal);   //n 为需要移动的圆盘的数量, source 为最开始的圆盘所在柱子的编号,
                                          //temp 为中转的圆盘的柱子的编号, goal 为最终圆盘所在的所在柱子的编号
void moveTower(int n, char source, char temp, char goal);

int main()
{
    int n;

    printf("Please enter the number of disks:");
    scanf("%d", &n);
    printf("Steps of moving %d disks from A to C by means of B:\n", n);

    moveTower(n, 'A', 'B', 'C');

    return 0;
}

void move(int n, char source, char goal)
{
    printf("Move %d: %c to %c\n", n, source, goal);
}

void moveTower(int n, char source, char temp, char goal)
{
    if(n == 1)
      move(n, source, goal);
    else
    {
      moveTower(n - 1, source, goal, temp);
      move(n, source, goal);
      moveTower(n - 1, temp, source, goal);
    }
}

万千只cnm 发表于 2021-5-10 21:25:33

https://www.bilibili.com/video/BV17s411N78s?p=35
页: [1]
查看完整版本: C语言递归小问题