递归-汉诺塔
#A:起始,B:中間,C:最后
count=0
def hanoi(n,A,B,C):
global count
if n==1:
print("{}:{}->{}".format(1,A,C))
count+=1
else:
hanoi(n-1,A,C,B) #將前n-1個盤子從A移動到B上
print("{}:{}->{}".format(n,A,C)) #將最底下的最后一個盤子從A移動到C上,同一個級別下上一條語句內執行的參數變化,不影響下一條變量。或變量沒有重新賦值?
count+=1
hanoi(n-1,B,A,C) #將B上的n-1個盤子移動到C上
hanoi(4,"A","B","C")
print(count)
count=0
def hanoi(n,A,B,C):
global count
if n==1:
print("{}:{}->{}".format(1,A,C))
count+=1
else:
hanoi(n-1,A,C,B) #將前n-1個盤子從A移動到B上
print("{}:{}->{}".format(n,A,C)) #將最底下的最后一個盤子從A移動到C上,同一個級別下上一條語句內執行的參數變化,不影響下一條變量。或變量沒有重新賦值?
count+=1
hanoi(n-1,B,A,C) #將B上的n-1個盤子移動到C上
hanoi(4,"A","B","C")
print(count)
轉載于:https://www.cnblogs.com/oycc2000/p/11241953.html
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
- 上一篇: 操作系统核心原理-5.内存管理(下):段
- 下一篇: 导数--基本概念