【发布时间】:2021-08-20 06:40:39
【问题描述】:
这是我的代码:
#include<stdio.h>
int move_disks(int, char, char, char);
int main()
{
int num;
char a='A',b='B',c='C';
printf("Enter the number of disk: ");
scanf("%d",&num);
printf("\nThe sequence of movement of disks are:\n");
move_disks(num, a, b, c);
return 0;
}
int move_disks(int num, char source_peg, char aux_peg, char to_peg)
{
if(num == 1)
{
printf("\nMove disk 1 from peg %c to peg %c.", source_peg, to_peg);
return;
}
move_disks(num - 1, source_peg, to_peg, aux_peg);
printf("\nMove disk %d from peg %c to peg %c.", num, source_peg, to_peg);
move_disks(num - 1,aux_peg, source_peg, to_peg);
}
我的输出是这样的:
Enter the number of disk: 3
The sequence of movement of disks are:
Move disk 1 from peg A to peg C.
Move disk 2 from peg A to peg B.
Move disk 1 from peg C to peg B.
Move disk 3 from peg A to peg C.
Move disk 1 from peg B to peg A.
Move disk 2 from peg B to peg C.
Move disk 1 from peg A to peg C.
在输出中,在“将磁盘 1 从 peg C 移动到 peg B”行中。我无法理解这是怎么发生的,因为在 if 语句中的递归函数代码中“printf(”\n将磁盘 1 从 peg %c 移动到 peg %c。”,source_peg,to_peg);"这是打印语句,在任何递归调用中,我从不将“peg C”作为源 peg 传递。
【问题讨论】:
-
谷歌河内塔,你会发现大量的信息。
标签: c dynamic-programming towers-of-hanoi