python中汉诺塔问题的求解
汉诺塔问题是源于印度一个古老传说的益智玩具。大梵天创造世界的时候做了三根金刚石柱子,在一根柱子上从下往上按照大小顺序摞着64片黄金圆盘。大梵天命令婆罗门把圆从下面开始按大小顺序重新摆放在另一根柱子上。并且规定,在小圆盘上不能放大圆盘,在三根柱子之间一次只能移动一个圆盘。
(a)是初始状态,也就是递归的起点,我们假设n=4, move(4,A,B,C)
<这个函数要实现的功能是把n个环从A按照一定的规则,借助B,移动到C>
(b)是step1完成的时候的状态,已经将所有的n-1,这里也就是3个环从A挪到了B
<第一处递归,move(n-1,A,C,B) 这个函数要实现将n-1个环从A,借助C,移动到B>
(c)是step2,此时需要将第n个,也就是第四个最大的环从A挪到C
<move(1,A,B,C),或者干脆直接print("A ->C")>
(d)是step3,此时需要将B上面的n-1个环从B挪到C<第二处递归>
<第二处递归,move(n-1,B,A,C) 这个函数要实现将n-1个环从B,借助A,移动到C>
代码如下:
# the numbering of plate -- n
def move(n,pos_from,pos_to):
print('the ',n,' plate move from ',pos_from,' to ',pos_to)
# the num of plates--n
def Hanio(n,start_pos,tran_pos,end_pos):
if n == 1:
move(n,start_pos,end_pos)
return
else:
Hanio(n-1,start_pos,end_pos,tran_pos)
move(n,start_pos,end_pos)
Hanio(n-1,tran_pos,start_pos,end_pos)
num=input('please input a num:')
n = int(num)
if n <= 0:
print("invalid input")
else:
Hanio(n,'A','B','C')
def move(n,pos_from,pos_to):
print('the ',n,' plate move from ',pos_from,' to ',pos_to)
# the num of plates--n
def Hanio(n,start_pos,tran_pos,end_pos):
if n == 1:
move(n,start_pos,end_pos)
return
else:
Hanio(n-1,start_pos,end_pos,tran_pos)
move(n,start_pos,end_pos)
Hanio(n-1,tran_pos,start_pos,end_pos)
num=input('please input a num:')
n = int(num)
if n <= 0:
print("invalid input")
else:
Hanio(n,'A','B','C')