汉诺塔问题

来源:互联网 发布:如何引出大数据 编辑:程序博客网 时间:2024/05/22 14:04

汉诺塔问题关键技术:为了将N个盘子从A移动到C,需要现将N-1个盘子移动到B上,这样才能将第N个盘子移动到C上。同理,为了将N-1个盘子从B移动到C上,需要将N-2个盘子移动A上,这样才能将N-1个盘子移动到C上。
利用函数的迭代来求解。

public class Hanoi {    public static void main(String[] args) {        int nDisks = 3;        moveDish(nDisks, 'A', 'B', 'C');    }    public static void moveDish(int level,char from,char inter,char to) {        if (level == 1) { // 如果只有一个盒子            System.out.println("从 " + from + " 移动盒子 " + level + " 号到 " + to);        } else {            moveDish(level - 1, from, to, inter);            System.out.println("从 " + from + " 移动盒子 " + level + " 号到 " + to);            moveDish(level - 1, inter, from, to);        }    }}
0 0
原创粉丝点击