我在理解此Hanoi塔递归算法时遇到问题:
public class MainClass { public static void main(String[] args) { int nDisks = 3; doTowers(nDisks, 'A', 'B', 'C'); } public static void doTowers(int topN, char from, char inter, char to) { if (topN == 1){ System.out.println("Disk 1 from " + from + " to " + to); }else { doTowers(topN - 1, from, to, inter); System.out.println("Disk " + topN + " from " + from + " to " + to); doTowers(topN - 1, inter, from, to); } } }
输出为:
Disk 1 from A to C Disk 2 from A to B Disk 1 from C to B Disk 3 from A to C Disk 1 from B to A Disk 2 from B to C Disk 1 from A to C
我不明白我们如何获得:
Disk 1 from C to B Disk 3 from A to C Disk 1 from B to A
有人可以解释一下吗?
谢谢。
通过将N-1个塔(除最后一个以外的所有磁盘)从A移到B,然后将第N个磁盘从A移到C,最后将先前移动的塔移动到钉,将N个磁盘的塔从钉A移到C。 B,从B到C。只要移动一个带有多个磁盘的塔筒,就可以应用此方法;对于1个磁盘塔筒,只需移动其唯一的磁盘。