汉诺塔

汉诺塔

关于汉诺塔的传说:
汉诺塔:汉诺塔(又称河内塔)问题是源于印度一个古老传说的益智玩具。大梵天创造世界的时候做了三根金刚石柱子,在一根柱子上从下往上按照大小顺序摞着64片黄金圆盘。大梵天命令婆罗门把圆盘从下面开始按大小顺序重新摆放在另一根柱子上。并且规定,在小圆盘上不能放大圆盘,在三根柱子之间一次只能移动一个圆盘。
接下来实现汉诺塔
C语言:

#include<stdio.h>

static int times = 1;

void hannoi(int num, char A, char B, char temp)
{	// 参数含义:把 A 上的 num 个盘子借助于 temp 移动到 B
	if(num == 1){
		printf("The %d Times move : %c ==> %c\n", times, A, B);
		times++;
	} else {
		// 先把 A 除最后一个通过 temp 移动到 B
		hannoi(num-1, A, temp, B);
		// 再把 A 的最后一个通过 B 移动到 temp
		hannoi(1, A, B, temp);
		// 最后把 temp 上面的通过 A 移动到 B, 即完成了 A 移动到 B 
		hannoi(num-1, temp, B, A);
	}
}

int main(){
	hannoi(3, 'A', 'B', 'C');
	
	return 0;
}  
/* Code Running Results:
 * The 1 times move: A ==> B
 * The 2 times move: A ==> C
 * The 3 times move: B ==> C
 * The 4 times move: A ==> B
 * The 5 times move: C ==> A
 * The 6 times move: C ==> B
 * The 7 times move: A ==> B 
 */

Java 语言:

public class HannoiGame {
	static int times = 1;   // 记录移动次数
	public static void hannoi(int num, char A, char B, char temp) {
		// 参数含义:把 A 上的 num 个盘子借助于 temp 移动到 B
		if(num==1) { 
			System.out.println("The " + times + " times move: " + A + " ==> " + B);
			times++;
		} else {
			// 先把 A 除最后一个通过 temp 移动到 B
			hannoi(num-1, A, temp, B);
			// 再把 A 的最后一个通过 B 移动到 temp
			hannoi(1, A, B, temp);
			// 最后把 temp 上面的通过 A 移动到 B, 即完成了 A 移动到 B 
			hannoi(num-1, temp, B, A);
		}
	}
	public static void main(String[] args) {
		hannoi(3, 'A', 'B', 'C');
	}

}
/* Code Running Results:
 * The 1 times move: A ==> B
 * The 2 times move: A ==> C
 * The 3 times move: B ==> C
 * The 4 times move: A ==> B
 * The 5 times move: C ==> A
 * The 6 times move: C ==> B
 * The 7 times move: A ==> B 
 */

Python 语言:

def hannoi(num, src, dst, temp = None):
    '''参数含义:把src上的num个盘子借助于temp移动到dst'''
    global times
    assert type(num) == int, 'num must be integer'
    assert num > 0, 'num must > 0'
    if num == 1:
        print('The {0} Times move : {1}==>{2}'.format(times, src, dst))
        times += 1
    else:
        # 先把src除最下面的通过dst移动到临时temp
        hannoi(num-1, src, temp, dst)
        # 再把src最后一个移动到dst
        hannoi(1, src, dst)
        # 最后再把临时temp上面的通过src移动到dst
        hannoi(num-1, temp, dst, src)
times = 1 # 记录移动次数的变量
hannoi(3, 'A', 'C', 'B')
'''
The 1 times move : A ==> C
The 2 times move : A ==> B
The 3 times move : C ==> B
The 4 times move : A ==> C
The 5 times move : B ==> A
The 6 times move : B ==> C
The 7 times move : A ==> C
'''
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值