第 27 天: Hanoi 塔问题:
这个问题起源于一个类似传说故事,在Hanoi这个地方有一个寺庙,这里有3根柱子和64个大小不同的金碟子。每个碟子有一个孔可以穿过。所有的碟子都放在第一个柱子上,而且按照从上到下碟子的大小依次增大的顺序摆设。如下图:
现在,假定寺庙里的僧侣要移动这些碟子,将它们从最左边移动到最右边的柱子上。不过移动的规则如下:
1. 每次只能从一个柱子的最上面移动一个碟子到另外一个柱子上。
2. 不能将大碟子放到小碟子的上面。
咋一看代码很短,估计会很简单,但是仔细一看居然没看懂,又要仔细思考推理一下了。这也是一个递归的问题。
1、如果只有一个圆盘的话,那我们只需要把这唯一的一个圆盘从The source pole移动到The destination pole上。
2、如果有n个圆盘,那我们可以把问题规模缩小,看看如果只有n-1个圆盘的话怎么移动,想n-1个圆盘怎么移动时,可以考虑n-2个怎么移动…这样一直缩小问题规模直到缩小到n=1。这个思路可以运用递归来解决,n=1就是递归的边界。
3、要将The source pole塔座上的圆盘全部移动到塔座The destination pole上,中间必定要有一步是原本The source pole塔座上面的n-1个圆盘全部移动到了The intermediary pole塔座上,然后就可以将The source pole塔座上的最后一个圆盘n移动到The destination pole塔座上,然后就可以再把The intermediary pole上的n-1个圆盘移动到The destination pole上。然后再考虑那n-1个是怎么从The source pole移动到The intermediary pole的。
package day17;
public class Hanoi {
/**
*********************
* Move a number of plates.
*
* @param paraSource
* The source pole.
* @param paraIntermedium
* The intermediary pole.
* @param paraDestination
* The destination pole.
* @param paraNumber
* The number of plates.
*********************
*/
public static void hanoi(char paraSource, char paraIntermediary, char paraDestination,
int paraNumber) {
if (paraNumber == 1) {
System.out.println(paraSource + "->" + paraDestination + " ");
return;
} // Of if
hanoi(paraSource, paraDestination, paraIntermediary, paraNumber - 1);
System.out.println(paraSource + "->" + paraDestination + " ");
hanoi(paraIntermediary, paraSource, paraDestination, paraNumber - 1);
}// Of hanoi
/**
*********************
* The entrance of the program.
*
* @param args
* Not used now.
*********************
*/
public static void main(String args[]) {
hanoi('a', 'b', 'c', 3);
}// Of main
}// Of class Hanoi