Recursion example: Hanover tower
First, the rules of Hanover Tower:
- Rearrange the disks, starting from the bottom, in order of size, onto the other pole.
- You can’t enlarge a disk on a small disk, and you can only move one disk at a time between three columns
Now suppose there are a total of n disks:
-
When n = 2:
1. Move the disk from A->B
2. Move the large disk from A->C
3. Turn the disk from B->C
- When there are n plates:
Think of the top n minus 1 plates as a whole
1. Change n-1 disks from A->C->B (the original problem is 1 smaller in size)
2. Move the NTH plate from A->C (move one step)
3. Change n-1 small disks from B->A->C (the original problem is 1 smaller)
Code implementation:
Void Hanoi (int n,char a,char b,char C) {if (n > 2) {//1 Hanoi (N-1, A, C, B) from A->C->B; Printf ("moving from % C to % C \n", A, C); Hanoi (n-1, B, A, C); } } int main() { hanoi(5, 'A', 'B', 'C'); }Copy the code
Results obtained:
For details, please refer to the video of station B:www.bilibili.com/video/BV1uA…
\