汉诺塔问题的算法分析与实现(Java)

汉诺塔问题是源于印度一个古老传说的益智玩具。要求将圆盘从A柱移动到C柱规定,在小圆盘上不能放大圆盘,在三根柱子之间一次只能移动一个圆盘。

可以先通过3个盘子的hanoi游戏得出其算法步骤如下:

if n=1 , 直接将圆盘移到c棒
if n>1 , 
将A棒上的n-1个圆盘移到B棒上
将A棒上的1个圆盘移到C棒上
将B棒上的n-1个圆盘移到C棒上



(图:3个盘子时第一步和第二步如上图所示)


用Java的实现代码如下

package cn.myseu.test.hanoi;

public class Hanoi {
	public static void main(String[] args) {
		hanoi(3,'A','B','C');
	}
	
	/**
	 * the implementation of hanoi, move all the plates from stick-src to stick-dest
	 * @param n the amount of plates
	 * @param src the first stick
	 * @param assist the middle stick
	 * @param dest the destination stick
	 */
	public static void hanoi(int n,char src,char mid,char dest){
		if (n==1){
			move(src,dest);
		}
		else{
			//move n-1 plates from stick-src to stick-mid ,assisted by stick-dest
			hanoi(n-1,src,dest,mid);
			//move the left 1 plate to the stick-dest directly
			move(src,dest);
			//move the left n-1 plates from stick-mid to sitck-dest
			hanoi(n-1,mid,src,dest);
			
		}
	}
	
	public static void move(char src,char dest){
		System.out.println("Move the plate from " + src +" to "+" dest ");
	}
}


算法分析:

n = 1 时,只需要移动一次即可完成任务

n > 1 时,需要 (2^n -1) 次,该算法的时间效率为O(2^n)


补充一句:

对时间效率为指数级的O(2^n)算法,以及数量级等同于O(2^n)的O(n!)算法,用现在的计算机处理无法得到结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值