Hanoi is an ancient Indian legend of educational toys. The movement of Hanoi can also be seen as a recursive function.
We have a column numbered A, B, C, and all the discs from a to C can be described as:
If a has only one disc, it can be moved directly to C;
If a has N disks, it can be seen as a has 1 discs (chassis) + (N-1) discs, the first need to move (N-1) a disk to B, and then, the last disk of a is moved to C, and then the B (N-1) disc moved to C.
Write a function, given the input n, a, B, C, to print out the moving steps:
Move (n, a, B, c)
For example, enter move (2, ' A ', ' B ', ' C ') to print out:
A–> B
A–> C
B–> C
The code is implemented in the following way:
def
move(n, a, b, c):
if
n
=
=
1
:
print
a,
‘-->‘
,c
else
:
move(n
-
1
,a,c,b)
#首先需要把 (N-1) 个圆盘移动到 b
move(
1
,a,b,c)
#将a的最后一个圆盘移动到c
move(n
-
1
,b,a,c)
#再将b的(N-1)个圆盘移动到c
move(
4
,
‘A‘
,
‘B‘
,
‘C‘
)
Python implementation Hanoi