河内塔中圆盘的移动
请使用 F7 向我逐步解释递归过程。
我只是无法将回报与控制流联系起来。
#include<stdio.h>
#include<conio.h>
void t_of_h(char, char, char, int);
void main()
{
int n;
clrscr();
printf("Enter no of DISC in Tower of Hanoi : ");
scanf("%d",&n);
printf("\nTower of Hanoi using %d DISCS\n",n);
t_of_h('X', 'Y', 'Z', n);
getch();
}
void t_of_h(char p1, char p2, char p3, int n)
{
if(n==0)
printf("Unsuccessful move\n");
if(n==1)
printf("Move DISC from %c to %c\n",p1,p3);
else
{
t_of_h(p1,p3,p2,n-1);
t_of_h(p1,p2,p3,1);
t_of_h(p2,p1,p3,n-1);
}
}
Please explain to me the recursion process step by step using F7.
I just can't correlate the return with flow of control.
#include<stdio.h>
#include<conio.h>
void t_of_h(char, char, char, int);
void main()
{
int n;
clrscr();
printf("Enter no of DISC in Tower of Hanoi : ");
scanf("%d",&n);
printf("\nTower of Hanoi using %d DISCS\n",n);
t_of_h('X', 'Y', 'Z', n);
getch();
}
void t_of_h(char p1, char p2, char p3, int n)
{
if(n==0)
printf("Unsuccessful move\n");
if(n==1)
printf("Move DISC from %c to %c\n",p1,p3);
else
{
t_of_h(p1,p3,p2,n-1);
t_of_h(p1,p2,p3,1);
t_of_h(p2,p1,p3,n-1);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如何将 N 个磁盘从 A 塔移动到 B 塔?
代码是一个非常直接的实现。如果您假设可以将任意数量的磁盘从一个塔移动到另一个塔,那么这显然是有效的。如何将 N-1 个圆盘从 A 塔移动到 C 塔?好吧,你将 N-2 个圆盘从 A 塔移动到 B 塔,然后将第 N-1 个圆盘从 A 塔移动到 C 塔,然后将 N-2 个圆盘从 B 塔移动到 C 塔。然后重复...
最终,递归停止,因为您有一个磁盘要移动。
一个有趣的练习是“编写一个测试工具,确保不会做出无效的移动”。
好的 - 我已经运行了代码。其过程的可视化是可怕的。很难看出到底发生了什么。但它是算法功能的直接报告。现在怎么办?
1 个磁盘
2 个磁盘
请注意,它是将磁盘从 X 移动到 Z。如何将 2 个磁盘从 X 移动到 Z?将顶部圆盘从 X 移动到 Y。将底部圆盘从 X 移动到 Z。将原始顶部圆盘从 Y 移动到 Z。
3 个圆盘
How do you move N disks from tower A to tower B?
The code is a pretty direct implementation of that. If you assume that you can move an arbitrary number of disks from one tower to another, then this clearly works. How do you move N-1 disks from tower A to tower C? Well, you move N-2 disks from tower A to tower B, then move the N-1th disk from tower A to tower C, then move the N-2 disks form tower B to tower C. And repeat...
Eventually, the recursion stops because you have a single disk to move.
An interesting exercise is "write a test harness that ensures that no invalid moves are ever made".
OK - I've run the code. Its visualization of the process is gruesome. It is very hard to see what is going on. But it is a direct report of what the algorithm does. Now what?
1 disk
2 disks
Note that it is moving disks from X to Z. How do you move 2 disks from X to Z? Move the top disk from X to Y. Move the bottom disk from X to Z. Move the original top disk from Y to Z.
3 disks
使用F7?
如果您在理解递归时遇到困难,请拿出笔和纸并逐步执行该程序。使用正确的参数堆叠每个调用。
当你可以想象它时,它应该更简单。
Using F7?
Well if you are having trouble understanding the recursion, get out a pen and paper and step through the program. Stack each call with the correct arguments.
It should be simpler when you can visualise it.