要从任意位置求解河内塔,您可以使用类似于从标准起始位置开始工作的标准解决方案的递归过程。
它只是需要更通用一点。
编写一个递归过程moveDisks(最大大小,targetPeg)移动所有大小 maxSize到挂钩目标挂钩, 像这样:
找到最大的磁盘m这样m.size and m is not on 目标挂钩。如果没有这样的磁盘,则返回,因为所有大小maxSize已经在正确的地方了。
Let 来源挂钩成为钉子m目前是,并且让otherPeg成为那个不是的钉子来源挂钩 or 目标挂钩.
Call moveDisks(m.size-1, otherPeg)递归地将较小的磁盘移开。
Move m from 来源挂钩 to 目标挂钩.
Call moveDisks(m.size-1, targetPeg)递归地将较小的磁盘放在它们所属的位置。
在Python中,我会这样写。请注意,我对游戏状态使用了不同的表示形式,该表示形式更适合该算法,并且不允许任何非法位置:
#
# Solve Towers of Hanoi from arbitrary position
#
# diskPostions -- the current peg for each disk (0, 1, or 2) in decreasing
# order of size. This will be modified
# largestToMove -- move this one and all smaller disks
# targetPeg -- target peg for disks to move
#
def moveDisks(diskPositions, largestToMove, targetPeg):
for badDisk in range(largestToMove, len(diskPositions)):
currentPeg = diskPositions[badDisk]
if currentPeg != targetPeg:
#found the largest disk on the wrong peg
#sum of the peg numbers is 3, so to find the other one...
otherPeg = 3 - targetPeg - currentPeg
#before we can move badDisk, we have get the smaller ones out of the way
moveDisks(diskPositions, badDisk+1, otherPeg)
print "Move ", badDisk, " from ", currentPeg, " to ", targetPeg
diskPositions[badDisk]=targetPeg
#now we can put the smaller ones in the right place
moveDisks(diskPositions, badDisk+1, targetPeg)
break;
Test:
> moveDisks([2,1,0,2], 0, 2)
Move 3 from 2 to 0
Move 1 from 1 to 2
Move 3 from 0 to 1
Move 2 from 0 to 2
Move 3 from 1 to 2