本人比較笨,漢諾塔問題想了老久纔想明白。
假設有3個柱子,A,B,C
如果只有1個盤子,只要將盤子1從A移動到C。
如果有N個盤子,可以將N分成N-1,和最下面的N盤子。
要想將盤子N移動到C柱子,就必須將N-1移動到B柱子,其中需要藉助的是C柱子,然後將盤子N移動到C柱子上。
隨後將N-1個盤子藉助A柱子移動到C柱子。
這就是一次過程,隨後就是遞歸了。
代碼如下
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void hanoi(int n,char A,char B,char C)
{
if(n==1)
printf("Move sheet %d from %c to %c\n",n,A,C);
else
{
hanoi(n-1,A,C,B);
printf("Move sheet %d from %c to %c\n",n,A,C);
hanoi(n-1,B,A,C);
}
}
main()
{
int n;
do
{
printf("請輸入盤數:");
scanf ("%d",&n);
hanoi (n,'A','B','C');
}while(n);
}