递归总结二 汉诺塔问题

汉诺塔是貌似递归入门的引导题目,把这个过程写下来,mark一下递归。没别的用处。

package hanoi;

public class Hanoi {
	/**
	 * 以A表示起始柱子,C表示结果柱,B表示中间柱
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		int n = 4;
		hanio(n, 'A', 'C', 'B');
	}

	/**
	 * 递归步骤如下: 先将前n-1块盘子挪到中间柱 然后将最后一块盘子挪到结果柱 最后将前n-1块柱子从中间柱挪想结果柱就可以了
	 * 
	 * @param n
	 * @param start
	 * @param destination
	 * @param temp
	 */
	public static void hanio(int n, char start, char destination, char temp) {
		if (n <= 0) {
			System.out.println("输入盘子个数必须大于0");
			return;
		}
		if (n == 1) {
			move(1, start, destination);
		} else {
			hanio(n - 1, start, temp, destination);
			move(n, start, destination);
			hanio(n - 1, temp, destination, start);
		}

	}

	/**
	 * 拼成打印挪盘子过程,纯粹是好玩 呵呵 没别的用处 可能这个第几的英文特例还没考虑全
	 * 
	 * @param current
	 * @param start
	 * @param destination
	 */
	public static void move(int current, char start, char destination) {
		StringBuilder sb = new StringBuilder();
		sb.append("move ").append(current);
		if (current == 1)
			sb.append("st dish from ");
		else if (current == 2)
			sb.append("nd dish from ");
		else if (current == 3)
			sb.append("rd dish from ");
		else
			sb.append("th dish from ");
		sb.append(start).append(" to ").append(destination);
		System.out.println(sb.toString());
	}
}

 说明:大概是这个样子吧,跑了3 跟4 没有问题。没看别的,呵呵。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值