How do you move N disks from tower A to tower B?
- Move N-1 disks from tower A to tower C.
- Move the bottom disk from tower A to tower B.
- Move N-1 disks from tower C to tower B.
The code is a pretty direct implementation of that. If you assume that you can move an arbitrary number of disks from one tower to another, then this clearly works. How do you move N-1 disks from tower A to tower C? Well, you move N-2 disks from tower A to tower B, then move the N-1th disk from tower A to tower C, then move the N-2 disks form tower B to tower C. And repeat...
Eventually, the recursion stops because you have a single disk to move.
An interesting exercise is "write a test harness that ensures that no invalid moves are ever made".
OK - I've run the code. Its visualization of the process is gruesome. It is very hard to see what is going on. But it is a direct report of what the algorithm does. Now what?
1 disk
Enter no of DISC in Tower of Hanoi : 1
Tower of Hanoi using 1 DISCS
Move DISC from X to Z
2 disks
Enter no of DISC in Tower of Hanoi : 2
Tower of Hanoi using 2 DISCS
Move DISC from X to Y
Move DISC from X to Z
Move DISC from Y to Z
Note that it is moving disks from X to Z. How do you move 2 disks from X to Z? Move the top disk from X to Y. Move the bottom disk from X to Z. Move the original top disk from Y to Z.
3 disks
Enter no of DISC in Tower of Hanoi : 3
Tower of Hanoi using 3 DISCS
Move DISC from X to Z
Move DISC from X to Y
Move DISC from Z to Y
Move DISC from X to Z
Move DISC from Y to X
Move DISC from Y to Z
Move DISC from X to Z