漢諾塔應用到了最簡單的迭代,最基本的**如下:
defhannoi(n, a, c, b, step):
if n !=0:
hannoi(n - 1, a, b, c, step)
print("
moving form %s to %s
" %(a, b))
hannoi(n - 1, c, a, b, step)
hannoi(5, "
a", "
b", "
c")
然後看到有大佬放出了動畫演示的demo:
進一步我稍作修改,給盤子新增了五個顏色,並統計執行的步數:
#coding: utf-8
import
turtle
class
stack:
def__init__
(self):
self.items =
defisempty(self):
return len(self.items) ==0
defpush(self, item):
defpop(self):
return
self.items.pop()
defpeek(self):
ifnot
self.isempty():
return self.items[len(self.items) - 1]
defsize(self):
return
len(self.items)
def drawpole_3(): #
畫出漢諾塔的poles
t =turtle.turtle()
t.hideturtle()
defdrawpole_1(k):
t.up()
t.pensize(10)
t.speed(100)
t.goto(400 * (k - 1), 100)
t.down()
t.goto(400 * (k - 1), -100)
t.goto(400 * (k - 1) - 20, -100)
t.goto(400 * (k - 1) + 20, -100)
drawpole_1(0)
#畫出漢諾塔的poles[0]
drawpole_1(1) #
畫出漢諾塔的poles[1]
drawpole_1(2) #
畫出漢諾塔的poles[2]
def creat_plates(n): #
製造n個盤子
color_list = ("
black
", "
red", "
green
", "
blue
", "
yellow")
plates = [turtle.turtle() for i in
range(n)]
for i in
range(n):
plates[i].up()
plates[i].hideturtle()
plates[i].shape(
"square")
plates[i].shapesize(1, 8 -i)
plates[i].color(color_list[(i % 5)])
plates[i].goto(-400, -90 + 20 *i)
plates[i].showturtle()
return
plates
def pole_stack(): #
製造poles的棧
poles = [stack() for i in range(3)]
return
poles
def movedisk(plates, poles, fp, tp): #
把poles[fp]頂端的盤子plates[mov]從poles[fp]移到poles[tp]
mov =poles[fp].peek()
plates[mov].goto((fp - 1) * 400, 150)
plates[mov].goto((tp - 1) * 400, 150)
l = poles[tp].size() #
確定移動到底部的高度(恰好放在原來最上面的盤子上面)
plates[mov].goto((tp - 1) * 400, -90 + 20 *l)
def movetower(plates, poles, height, frompole, topole, withpole): #
遞迴放盤子
global
step
if height >= 1:
movetower(plates, poles, height - 1, frompole, withpole, topole)
movedisk(plates, poles, frompole, topole)
step = step + 1poles[topole].push(poles[frompole].pop())
movetower(plates, poles, height - 1, withpole, topole, frompole)
return
step
my_screen =turtle.screen()
drawpole_3()
n = int(input("
請輸入漢諾塔的層數並回車:\n"))
plates =creat_plates(n)
poles =pole_stack()
step = 0 #
記錄移動總步數
for i in
range(n):
poles[0].push(i)
steps = movetower(plates, poles, n, 0, 2, 1)
my_screen.exitonclick()
print("
該過程共移動 %s 步
" % steps)
由於採用了上面大佬的**,最多限制8個盤子。
漢諾塔 遞迴演算法
個人覺得漢諾塔這個遞迴演算法比電子老鼠的難了一些,不過一旦理解了也還是可以的,其實網上也有很多 可以直接參考。記得大一開始時就做過漢諾塔的習題,但是那時 寫得很長很長,也是不理解遞迴的結果。現在想起來漢諾塔的演算法就3個步驟 第一,把a上的n 1個盤通過c移動到b。第二,把a上的最下面的盤移到c。第...
漢諾塔遞迴演算法
大學的時候專業課程很差,指導大二學習演算法設計的時候,發現專業課裡比較有趣的一門。專心學習了一學期 最近在學習python發現了乙個遞迴演算法很迷茫,遂研究了一下。簡單來說明一下 首先漢諾塔的規則是1 每次移動一塊 2 小木塊只能放在大木塊上 3 將所有木塊從a柱子移動c柱子木塊上 用幾個變數和常量...
漢諾塔 遞迴
個人理解遞迴函式的基本要求就是,函式中呼叫函式本身,滿足特定的條件後返回。include include include include include include include include include include include include include 標頭檔案引用的較多...