如何解决在给定的代码行中递归是如何发生的?
谁能告诉我这行代码是如何工作的?
在这个给定的代码中,函数是如何执行的? 即塔(n-1,源极,辅助极,目的地极);在这一部分中,如何排列值从而产生上述输出。
https://www.geeksforgeeks.org/recursive-functions/
#include<stdio.h>
// Assuming n-th disk is bottom disk (count down)
void tower(int n,char sourcePole,char destinationPole,char auxiliaryPole)
{
// Base case (termination condition)
if(0 == n)
return;
// Move first n-1 disks from source pole
// to auxiliary pole using destination as
// temporary pole
tower(n-1,sourcePole,auxiliaryPole,destinationPole);
// Move the remaining disk from source
// pole to destination pole
printf("Move the disk %d from %c to %c\n",n,destinationPole);
// Move the n-1 disks from auxiliary (Now source)
// pole to destination pole using source pole as
// temporary (auxiliary) pole
tower(n-1,destinationPole,sourcePole);
}
int main()
{
tower(3,'S','D','A');
return 0;
}
输出是
Move the disk 1 from S to D
Move the disk 2 from S to A
Move the disk 1 from D to A
Move the disk 3 from S to D
Move the disk 1 from A to S
Move the disk 2 from A to D
Move the disk 1 from S to D
解决方法
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。