Python algorithm - Recursive fine solution - Tower of Hanoi problem

Tower of Hanoi problem

The meaning of problems

A column on the block transferred to the C

Condition 1 - Each can only transfer a

Condition 2 - the pressure is not small chunks faster

Resolve

Concept principle

Elephants refrigerator loaded question

1. Open the refrigerator

2. Insert elephant

3. Close the refrigerator 

In analogy any one block is n

1. The above blocks are moved good

2. n blocks move past

3. Before block above block on top n

Simplify the problem, consider moving the 123 can be considered as I want to move 3 is bound to move 12

Similarly I want to move 2, will have to move 1 , that relationship

f (3) ---> f (2) ---> f (1) issues into separate Scheme 3, 2, 1, i.e., reverse primer push

f (3) ==> f (1) + premise (2) is 2,1 to 3 Problem

f (2) ==> f (1) 2 provided that issues a block processing

Flow analysis

The employer to describe it, each block has a worker responsible for

N Three workers the ability to

1. The n-th block can only be moved to any post

2. n can ask workers to help him in his above process pressure block (n-1 treated for workers)

3. n is the final work on the workers move to the target n-th column block

Moving the time to determine which columns of which column you want to move.

There are three pillars title. The first pillar starting third goal post, and that the rest is a transfer column

The column can be transferred as a transit point, the ultimate goal is to have three columns.

Prior to Step Three. Only the upper two blocks are placed in a column transit

Code

DEF HNT (index, Start, MID, End):
     # last man only one job is to move to the end of the first block 
    IF index ==. 1 :
         Print  " {} ---> {} " .format (Start, End)
     the else :
         # someone to move the upper block, the first transfer done on the mid 
        HNT (index -. 1 , Start, End, mid)
         # themselves to block their move to the target column 
        Print  " {} - -> {} " .format (start, End)
         # as people move back to the previous block, prior to the mid, End now on, use the start relay 
        HNT (index -. 1 , mid, start, End) 


IF  the __name__ == ' __main__ ' : 
    HNT (3, "A", "B", "C")
    
    # A--->C
    # A--->B
    # C--->B
    # A--->C
    # B--->A
    # B--->C
    # A--->C

 

Guess you like

Origin www.cnblogs.com/shijieli/p/12606985.html