-1

这是我为河内塔问题编写的 Python 代码,其中必须将塔从左边的钉子转移到中间的钉子上,使用右边的钉子作为备用:

def hanoi(n, origin = "1", destination = "2", spare = "3"):

    if n == 1:
        print ("Move disk from", origin, "to", destination)

    else:
        hanoi(n-1, origin, spare, destination)
        hanoi(1, origin, destination, spare)
        hanoi(n-1, spare, destination, origin)

hanoi(3)

现在我的教授希望我以合法移动仅从塔 1 到 2、塔 2 到 3 和塔 3 到 1 的方式实施它。所有其他规则都是相同的。

4

1 回答 1

4

与此问题一样,您需要进行归纳思考。从最小的塔开始移动,然后问自己:如果我能做到,我该如何移动更大的塔?

由于移动大小为 1 的塔是微不足道的,让我们从大小为 2 的塔开始:

基本情况

将一个大小为 2 的塔向右移动:

|  -  |     |     |
| --- |     |     |
-------------------
Step 1:

|     |     |     |   
| --- |  -  |     |
-------------------
Step 2:

|     |     |     |
| --- |     |  -  |
-------------------
Step 3:

|     |     |     |
|     | --- |  -  |
-------------------
Step 4:

|     |     |     |
|  -  | --- |     |
-------------------
Step 5:

|     |  -  |     |
|     | --- |     |
-------------------

这演示了如何将塔的一个钉子向右移动。当然,这也可以用于将塔从第二个钉子移到第三个钉子,或从第三个钉子移到第一个钉子。

假设你知道如何将一个大小为n的塔向右移动一个钉子,下面是你对n + 1 个磁盘的操作方法:

|    -    |         |         | Move the small tower one peg to the right
|   ---   |         |         |
|  -----  |         |         |
| ------- |         |         |
-------------------------------
Step 1:

|         |         |         | Move it another step to the right
|         |    -    |         |
|         |   ---   |         |
| ------- |  -----  |         |
-------------------------------
Step 2:

|         |         |         | Let's move the n+1 disk one peg to the right
|         |         |    -    |
|         |         |   ---   |
| ------- |         |  -----  |
-------------------------------
Step 3:

|         |         |         | Move the small tower to the right
|         |         |    -    |
|         |         |   ---   |
|         | ------- |  -----  |
-------------------------------
Step 4: 

|         |         |         | Move the small tower another peg to the right
|    -    |         |         |
|   ---   |         |         |
|  -----  | ------- |         |
-------------------------------
Final step:

|         |    -    |         | 
|         |   ---   |         |
|         |  -----  |         |
|         | ------- |         |
-------------------------------
于 2012-11-24T15:17:18.317 回答