【问题标题】:How Recursion is taking place in given lines of code?在给定的代码行中递归是如何发生的?
【发布时间】:2021-07-10 03:10:48
【问题描述】:

谁能告诉我这行代码是如何工作的?

在这个给定的代码中,函数是如何被执行的? 即 tower(n-1, sourcePole, assistantPole,destinationPole);在这部分中,值是如何排列从而产生上述输出的。

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,sourcePole, destinationPole);
 
   // Move the n-1 disks from auxiliary (now source)
   // pole to destination pole using source pole as
   // temporary (auxiliary) pole
   tower(n-1, auxiliaryPole, 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

【问题讨论】:

  • 当函数调用自身时会发生递归。因此,当tower() 再次调用tower() 时,递归发生在给定代码中的两个位置。这就是递归的工作原理。该算法非常透明。如果您无法在脑海中看到它,请拿起铅笔并手动执行说明。
  • 好的,那么在调用过程之后 printf() 函数是如何产生这个输出的呢?
  • 因为函数返回,然后 printf 被发出。诀窍是顶部的守卫if( n==0) 防止它永远递归。
  • 好的,理解这段代码需要哪些先决条件?
  • 逻辑和对 C 语法的基本了解。第一次调用时的参数是什么? n 是什么?接下来发生什么? cmets 实际上准确地解释了正在发生的事情。

标签: c function recursion data-structures


【解决方案1】:

尝试从图片中理解:

【讨论】:

  • 请将图片添加为图片而不是链接。在我看来,答案可能会有所帮助,但似乎因为没有人点击的单个链接而被否决了。对图像进行一些文字说明会更好。
猜你喜欢
  • 1970-01-01
  • 2015-07-23
  • 2016-10-18
  • 2023-01-20
  • 2010-09-07
  • 2012-08-31
  • 1970-01-01
  • 2021-01-11
  • 1970-01-01
相关资源
最近更新 更多