python algorithm - Tower of Hanoi problem

Tower of Hanoi problem

 

Initial state:

 

Thinking: When the number of plates is 3 , write down the order of movement

Steps to move:

3 plates, from a to c

1. The first two plates, from a to b

1 ) Put a plate in front, from a to c

a->c

2 ) put the second plate, from a to b

a->b

3 ) put the plate on c, from c to b

c->b

2. The last plate, from a to c

a->c

3. Put the two plates on b, from b to c

1 ) put a plate in front, from b to a

b->a

2 ) put the second plate, from b to c

b->c

3 ) put the plate on a, from a to c

a->c

 

 

 

Summarize:

n plates, from a to c

1 , n-1 plates from a to b

2. The last plate, from a to c

3. n-1 plates from b to c

 

Code:

# encoding=utf-8

 

def hanoi(n,a,b,c):

    if n == 1:

        print a,'->',c

    else:

        hanoi (n -1 , a, c, b)

        hanoi ( 1 , a, b, c)

        hanoi (n -1 , b, a, c)

 

if __name__ == '__main__':

    hanoi ( 3, ' a ' , ' b ' , ' c ' )

 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325096911&siteId=291194637