How is Hanoi implemented by recursive algorithms?
This question bothered me for a while, and today I think it seems clear, so I'm going to record my thoughts here.
First, put the code on Python:
1 #-*-coding:utf-8-*-2 3 defMove (n,a,b,c):4 ifn = = 1:5 Print(A +" -"+c)6 ifn > 1:7Move (n-1, A,c,b)8 Print(A +" -"+c)9Move (n-1, B,a,c)Ten OneMove (4,'A','B','C')
In order to complete this task, this parent task needs to be decomposed into three subtasks:
1. Move the n-1 on top of A to B
2. Move the bottom nth disk of a "to C"
3. Move the n-1 disk from B to C on the first step, and the task is completed.
The first task is to move the n-1 disk to B, through the code:
Move (N-1,A,C,B)
This is to tell the computer, one piece at a time, a n-1 on a disk to B, can be seen as a step to complete.
Next, move the nth disk in A to C:
Print (A +"--"+c)
At last:
Move (N-1,B,A,C)
Move all n-1 disks on B to C to complete the task.
Recursive algorithm of Hanoi