河内塔问题
You are challenged for a challenge to find the number of moves required to move a stack of disks from one peg to another peg. Wait for a second, it sounds easy? Let’s find are what is going on and in this article, we are introducing a chapter of "TOWER OF HANOI".
您面临一项挑战,即寻找将一叠磁盘从一个钉移到另一个钉所需的移动次数。 等待一秒钟,听起来很简单? 让我们找到正在发生的事情,在本文中,我们将介绍“ TOWER OF HANOI”一章。
You are given with a stack of n disks on a peg arranges as largest is at the bottom and smallest is at the top. We are required to shift this whole stack to another peg (total three pegs, two are empty initially) with considering the following rule:
您会得到一堆n块磁盘,它们在钉子上排列,最大的在底部,最小的在顶部。 我们需要考虑以下规则,将整个堆栈移动到另一个钉子(总共三个钉子,最初两个是空的):
No larger disk can be placed over a smaller one.
较大的磁盘不能放在较小的磁盘上。
One disk at a time.
一次一个磁盘。
The problem is looking easy but it's not. The way we are going to tackle it is recursion. The problem is simple when you see it from recursion perspective.
问题看起来很简单,但事实并非如此。 我们要解决的方法是递归。 从递归角度看时,问题很简单。
Key: The number of steps required to shift the stack is exactly equal to the twice of steps for shifting the stack of one less disk(The largest one) plus one step.
关键:移位堆栈所需的步骤数完全等于移位少一个磁盘(最大的磁盘)加一级的步骤的两倍。
Consider the case of shifting one disk : T(1) = 1Consider the case of shifting two disk : T(2) = 2*T(1) + 1 = 3Consider the case of shifting three disk : T(3) = 2*T(2) + 1 = 7.... T(n) = 2*T(n-1) + 1
Implementing this formula now in our python program is our next goal of solving this.
现在在我们的python程序中实现此公式是解决此问题的下一个目标。
So here is the code:
所以这是代码:
def hanoi(x):
if x == 1:
return 1
else:
return 2*hanoi(x-1) + 1
x = int(input("ENTER THE NUMBER OF DISKS: "))
print('NUMBER OF STEPS: ', hanoi(x))
Output:
输出:
ENTER THE NUMBER OF DISKS: 5
NUMBER OF STEPS: 31
翻译自: https://www.includehelp.com/python/tower-of-hanoi.aspx
河内塔问题