Take you to understand Hanoi Tower of Hanoi recursive algorithm

1. Hanoi problem caused by the game

The Tower of Hanoi is a question based on a legend. The issue of the Tower of Hanoi (also known as the Tower of Hanoi) is an educational toy derived from an ancient legend in India. When the Brahma created the world, he made three diamond pillars. On one pillar, 64 golden discs were stacked in order of size from bottom to top. The Great Brahma ordered the Brahmin to re-place the disc on another pillar in order of size from below. It is also stipulated that the disc cannot be enlarged on the small disc, and only one disc can be moved between the three pillars at a time.

2. A mathematical problem

0000

We abstract the Hanoi problem as a mathematical problem. First, the following three pillars A, B, and C are given, among which there are N cloud disks stacked from top to bottom from small to large on the A column. Now it is required to move the discs on the A pillar to the C pillar, where each movement must meet:

  1. Only one disc can be moved at a time
  2. The small disk cannot be enlarged

Then for this mathematical problem, you can ask related questions:

  1. How many times is required to move N discs at least
  2. Which disk is moving in step M and the direction in which the disk is moving
Problem solving:

Suppose there are a total of N discs, Steps represents the total number of moves

1. For question 1

(1)if N == 1

第1次 1号盘 A—->C 
Steps = 1 次

(2)if N == 2

11号盘 A—->B22号盘 A—->C31号盘 B—->C 
Steps = 3

(3)if N == 3

11号盘 A—->C
​第22号盘 A—->B
​第31号盘 C—->B
​第43号盘 A—->C
​第51号盘 B—->A
​第62号盘 B—->C
​第71号盘 A—->C 
Steps = 7

Push down one by one, and you can find that the number of discs N and the total number of movements have such a law

1个圆盘的次数 21次方减1
2个圆盘的次数 22次方减1
3个圆盘的次数 23次方减1...
...
...
​n个圆盘的次数 2的n次方减1

So an equation relationship can be drawn: Steps=2n1 S t e p s = 2 n − 1

2. For question 2

We used 数学归纳法to understand the Hanoi recursive algorithm. For recursion, it means that the method calls itself internally, and there must be an end point. Partners who have studied assembly language should know that each recursive call is actually a stack operation, and this recursive call is actually a process of method call stack. In each call, the method is called from the main thread and the stack is pushed and popped continuously. Among them, the transfer of the method is to push the method into the stack, and the end of the method is the process of the method being unstacked. This can ensure the sequence flow of method calls, that is, when the function has multiple levels of nesting, the function needs to be pushed into the stack from outside to inside, and the function at the top of the stack is executed first (the innermost function is executed first) After the end), the stack is popped, and then the function execution of the penultimate layer is finished. At the end, the first function call to the stack is popped from the stack back to the main thread and ends.

The characteristic of the stack is: FIFO (first in last out). For example, a method calls itself, and one of the calling processes is the stacking process: A->A(1)->A(2)->A(3)

When A(3) meets certain conditions, it can exit, return to A(2), A(2) ends back to A(1), and then back to A, the stack process: A(3)->A(2 )->A(1)->A

So, let’s now look at Hanoi’s recursive problem. First, let’s look at the implementation of the current Hanoi’s recursive algorithm.

### move_hanoi.py
def move(num,go,to):
    global i
    i=i+1
    print('第{}步--移动 {} 号圆盘:'.format(i,num), 'move',go,'to',to)
def hanoi(num,a,b,c):
    if num == 1:
        move(num,a,c)
        return
    hanoi(num-1,a,c,b)
    move(num,a,c)
    hanoi(num-1,b,a,c)

hanoi_move(5,'A','B','C')
i=0

The output effect is as follows
0001

Does it seem simple? At that time, I couldn't understand why this is the recursion. In fact, after listening to the teacher mentioning it many times, it felt like I was ignorant and pretended to understand. If I did not understand, I still need to try and explore. Passing proof may be a good way.

In order to justify this recursive algorithm can be used 数学中归纳法to understand. For recursive algorithm problems, don't think of tracking the entire recursive call from the beginning. There are many very vivid descriptions on Zhihu . In fact, if it is for Hanoi mobile with less than three disks, it is actually easy to understand. But when the number increases, it becomes more complicated to think about this problem, which is why we need to understand from the transfer between layers, rather than expand the entire recursion.

Discuss now, when only one disc needs to be moved, at this time N = 1
only needs to move once, that is, move the first disc from A to C

步骤  圆盘  柱子移动方向
1     1     A -> C

When moving two plates, N = 2

步骤  圆盘  柱子移动方向
1    1     A -> B2    2     A -> C3    1     B -> C

When moving three discs, at this time N = 3

步骤  圆盘  柱子移动方向
1     1     A -> C
2     2     A -> B3     1     C -> B
4     3     A -> C
5     1     B -> A
6     2     B -> C
7     1     A -> C

According to the above movement, we summarize the law of disc movement:

  • In the movement record, when the number of the plate and the number of the plate are the same, their steps are all moving from A to C
  • Other steps are equivalent

Observe steps 1-3 and steps 5-7 in the third case

  • Steps 1-3: The goal is to move from A to B. If we regard B as the end point, then steps 1-3 here are exactly the same as the three steps of moving two discs.

    步骤  圆盘  柱子移动方向  B、C 互换
    1       1     A  -> C     (A -> B) 
    2       2     A ->  B     (A -> C) 
    3       1     C ->  B     (B -> C)
    
    即此时相当于 (XCHG B,C),将 B、C 进行了互换
  • Steps 5-7: The goal is to move from B to C. If we take C as the end point, then the 5-7 steps here are exactly the same as the three steps of moving two discs.

    步骤  圆盘  柱子移动方向  B、A 互换
    5       1     B  -> A     (A -> B) 
    6       2     B ->  C     (A -> C) 
    7       1     A ->  C     (B -> C)
    
    即此时相当于 (XCHG B,A),将 B、A 进行了互换

    Then, we can summarize the law obtained above as

    • 1. There is only one disc, Steps=1, move from A to C to end
    • 2. When there are N disks, Steps=2^n-1 is an odd number, and all actions in the middle are all moving from A to C
    • 3. All intermediate actions can be considered as: move from A to B
    • 4. All intermediate actions can be considered as: move from B to C

We use pseudo code to express the above law

Function MOVE(N,A,B,C)
    IF N ==1 THEN
        Print A;"TO",C
    ELSE 
        CALL MOVE(N-1,A,C,B);//MOVE(N,A,B,C)中 B、C 互换,N=N-1
        Print A;"TO",C
        CALL MOVE(N-1,B,A,C);//MOVE(N,A,B,C)中 B、A 互换,N=N-1
    END IF

This is the induction process of Hanoi's recursive algorithm

Data reference:

  1. Hanruota Interactive Encyclopedia
  2. Function call stack analysis + diagram

Guess you like

Origin blog.csdn.net/qq_36148847/article/details/80783521