问题描述
谁能告诉我这行代码是如何工作的?
在这个给定的代码中,函数是如何执行的? 即塔(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