Preface
This series of articles is the author's notes on learning data structure, please correct me if there is anything wrong
table of Contents
Question stem
Description
The Tower of Hanoi is a toy derived from Indian mythology.
God created the world because Oh Hu made three pillars. On one of the pillars, 64 golden discs were stacked in order of size from top to bottom.
God ordered the Brahman to re-place the discs on another pillar in order of size from the bottom, requiring that the small discs cannot be enlarged and only one disc can be moved at a time.
Input
Enter the number of sequins n. Here n<=10.
Output
Output the whole process of moving sequins. See the sample format.
Sample
Input
2
Output
Move disk 1 from A to B
Move disk 2 from A to C
Move disk 1 from B to C
analysis
According to the law,
if it is a plate,
directly move the plate of the A column to the C column,
otherwise
first move the n-1 plate of
the A column with the help of C to B, move the plate of the A column from A to C and
finally move the n of the B column -1 plate moved to C with the help of A
- The above analysis is directly written in a recursive form
Code
#include<stdio.h>
void hannuota(int n,char ch1,char ch2,char ch3)
{
if(n==1) //如果是一个盘子
{
printf("Move disk %d from %c to %c\n",n,ch1,ch3); //直接将A柱的盘子移到C柱
}
else //否则
{
hannuota(n-1,ch1,ch3,ch2); //先将A柱的n-1个盘子借助C移到B
printf("Move disk %d from %c to %c\n",n,ch1,ch3); //将A柱的盘子从A移到C
hannuota(n-1,ch2,ch1,ch3); //最后将B柱的n-1个盘子借助A移到C
}
}
int main()
{
int n;
scanf("%d",&n);
hannuota(n,'A','B','C');
}
enter
3
Output
Move disk 1 from A to C
Move disk 2 from A to B
Move disk 1 from C to B
Move disk 3 from A to C
Move disk 1 from B to A
Move disk 2 from B to C
Move disk 1 from A to C