0
点赞
收藏
分享

微信扫一扫

Java题目合集【不断更新中...】

you的日常 2022-01-06 阅读 83

1.汉诺塔

package Test;

public class han {

	public static void main(String[] args) {
		hanoiTower(3, 'A', 'B', 'C');//num-->盘子个数

	}
	
	//汉诺塔的移动方法
	//使用分治算法
	
	public static void hanoiTower(int num, char a, char b, char c) {
		//如果只有一个盘
		if(num == 1) {
			System.out.println("第1个盘从" + a + "->" + c);
		} else {
			//如果我们有n>=2的情况,我们总是可以看作两个盘,(1)最下面的一个盘 (2)上面的所有盘
			//1.先把上面的所有盘移动到B,借助C
			hanoiTower(num - 1, a, c, b);
			//2.把最下面的盘子从A->C
			System.out.println("第" + num + "个盘从" + a + "->" + c);
			//3.把B塔所有的盘移动到C,借助A
			hanoiTower(num - 1, b, a, c);
		}
	}

}
举报

相关推荐

0 条评论