汉诺塔问题来自于一个古老的传说。传说印度的主神梵天做了一个汉诺塔,它是在一个黄铜板上插上3根宝石针,其中一根针上从上到下按从小到大的顺序串上了64个金片。梵天要求僧侣们轮流把金片在3根针之间移来移去,规定每次只能移动一片,且不许将大金片压在小金片上。
当金片的数量为 3个时,移动过程如下:
在金片移动的过程中,必定会剩下最后一个金片。
最后一个金片移动到目标位置。
此时就会发现问题复现了,接下来的操作就相当于要把余下的n-1个放到目标位置。
我们采用递归法,递归函数:
void move(int n, char start, char temp, char goal)
表示将第n个金片从起始位置经临界位置移动到目标位置。
想要剩下最后一个金片,先调用
move(n-1,start,goal,temp);
然后把最后一个金片移动到目标位置。
printf("Move disk %d from %c to %c\n",n,start,goal);
复现,只不过现在是从原来的临界经开始移动到目标位置。
move(n-1,temp,start,goal);
核心代码:
void move(int n, char start, char temp, char goal) {if(n>=1) {move(n-1,start,goal,temp);printf("Move disk %d from %c to %c\n",n,start,goal);move(n-1,temp,start,goal);}return;
}
演示:
#includevoid move(int n, char start, char temp, char goal) {if(n>=1) {move(n-1,start,goal,temp);printf("Move disk %d from %c to %c\n",n,start,goal);move(n-1,temp,start,goal);}return;
}int main() {int n;printf("请输入金片的片数:\n");scanf("%d",&n);printf("移动的方法如下:\n");move(n,'A','B','C');
}