假设柱子标为A,B。C。要由A搬至C,在仅仅有一个盘子时,就将它直接搬至C;当有两个盘子,就将B作为辅助柱。假设盘数超过2个。将第二个下面的盘子遮起来,就非常easy了。每次处理两个盘子,也就是:A->B、A->C、B->C这三个步骤,而被遮起来的部分,事实上就由方程的递归处理。
代码例如以下:
#include <stdio.h>
void hanoi(int n,char A,char B,char C){
if(n == 1){
printf("Move sheet %d from %c to %c
",n,A,C);
}
else{
hanoi(n-1,A,C,B);
printf("Move sheet %d from %c to %c
",n,A,C);
hanoi(n-1,B,A,C);
}
}
int main(){
int n;
printf("请输入盘数:");
scanf("%d",&n);
hanoi(n,'A','B','C');
return 0;
}
执行结果: