汉诺(Hanoi)塔问题。传说印度古代某寺庙中有一个梵塔,塔内有3个座A、B和C,座A上放着64个大小不等的盘,其中大盘在下,小盘在上。有一个和尚想把这64个盘从座A搬到座B,但一次只能搬一个盘,搬动的盘只允许放在其他两个座上,且大盘不能压在小盘上。现要求用程序模拟该过程,并输出搬动步骤。
#include<stdio.h>
void hanoi(int n,char a,char b,char c);
int main()
{
int n;
printf("Input the number of disk:\n");
scanf("%d",&n);
printf("The steps of %d disk are:\n");
hanoi(n,'a','b','c');
return 0;
}
void hanoi(int n,char a,char b,char c){
if(n==1)printf("%c-->%c\n",a,b);
else{
hanoi(n-1,a,c,b);
printf("%c-->%c\n",a,b);
hanoi(n-1,c,b,a);
}
}
输入样例:3
输出结果:
Input the number of disk:
The steps of 0 disk are:
a-->b
a-->c
b-->c
a-->b
c-->a
c-->b
a-->b