#-*-Coding:utf-8-*-# author:keekuun "" "There are three Poles a,b,c. A rod has N (n>1) perforated discs, the size of the disk from bottom to top in turn smaller. The following rules are required to move all discs to the C-bar: Only one disc can be moved at a time; the market cannot be stacked on a small plate. "" "Time = 0def mov (n, a, B, c): global" when there is only one disc if n = = 1: print (A, '--', B # when there are n disks when else: # n = (n-1) +1, first move the n-1 discs to B mov (n-1, A, C, b) # to move the largest disk 1 directly to C mov (1, a, B, c) # again Move the n-1 disk from B to C mov (n-1, B, A, c) return Timeprint (mov (1, ' A ', ' B ', ' C ')) print (' * ' *10) print (MOV (2, ' A ', ' B ', ' C ') Print (' * ' *10) print (MOV (3, ' A ', ' B ', ' C ')) print (' * ' *10) print (MOV (4, ' A ', ' B ', ' C '))
Output
A-and B
1
**********
A-and C
A-and B
B--A
4
**********
A-and B
A-and C
C--A
A-and B
B--C
B--A
A-and B
11
**********
A-and C
A-and B
B--A
A-and C
C--B
C--A
A-and C
A-and B
B--A
B--C
C--B
B--A
A-and C
A-and B
B--A
26
Hanoi recursive algorithm