无聊的蛋疼。
#!/usr/bin/env python
def Hanoi(n):
#递归解法
def han(A,B,C,n):
if n==1:
print n,A,"-->",C
else:
han(A,C,B,n-1)
print n,A,"-->",C
han(B,A,C,n-1)
han('A','B','C',n)
def Hanoi(n):
#非递归解法
even=('A','B','C')
odd=('A','C','B')
ls=[0 for i in range(n)]
for i in range(1,2**n):
deepth=n
a=i
while a&1==0:
deepth-=1
a=a>>1
temp=odd if deepth%2==1 else even
print n+1-deepth,temp[ls[deepth-1]%3],"-->",temp[(ls[deepth-1]+1)%3]
ls[deepth-1]+=1
模拟递归
def Hanoi(n):
a,b,c='A','B','C'
status=1#1 开始 2左分支完毕 3右分支完毕
stack=[]
while True:
#print a,b,c,status,n
#raw_input()
if n>1 and status==1:
#左分支
stack.append((a,b,c,status,n))
n-=1
a,b,c=a,c,b
elif n==1:
#底层
print n,a,"-->",c
a,b,c,status,n=stack.pop()
if status==1 or status==2:
status+=1
elif n>1 and status==2:
#右分支
print n,a,"-->",c
stack.append((a,b,c,status,n))
n-=1
a,b,c=b,a,c
status=1
else:
#回退
if len(stack)==0:
return
a,b,c,status,n=stack.pop()
if status==1 or status==2:
status+=1