Tower of Hanoi and Recursion | Jason Zhu’s Personal Website
Tower of Hanoi and Recursion
Tower of Hanoi is a device made up of three rods and several disks with different diameters.
While we initially put all disks at the leftmost rod, the smallest at the top, while largest at the bottom.
Rule of the Puzzle
Then, the objective of the puzzle is to move the entire stack to the last rod, not violating following rules, and you can refer to this illustration (source: wikipedia - Tower of Hanoi)
Only one disk may be moved at a time.
Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack or on an empty rod.
No disk may be placed on top of a disk that is smaller than it.
Recursive Solution to Hanoi Tower
Interestingly, the Tower of Hanoi is a classic example of using recusion solution.
Although the procedure count will grow exponentially with the increase in disk count, the logic of solving it is extremely straighforward.
We can split into two cases, the base case and the recursive case.
So, when we want to move “n” disks from one rod to another rod following the rules, there are two cases:
When there are zero disk, so n = 0, The puzzle is automatically solved
When n > 0, calling the not mentioned disk is the “third rod”. We need to do three steps:
move “n - 1” disks from starting rod to third rod
move the biggest disk on the bottom to the destination
move the remaining rod from third rod to destination
Yes, although this is somehow counterintuitive, by following these steps recursively, any kind of Hanoi Tower with three rods can be solved.
To illustrate this, so I used Processing to construct a program that follows such rule.
Code Implementation
First, here is the ultimate effect. Due to some mysterious bug, disks start from first and end at the second:
The disk class, which records relative information for a single disk:
The class for three rods, which helps to record the moving of the disks and illustrate the process:
The main class that initialize the settings and operates the moving (The code is not optimized since I first produce the moving sequence and then perform them in another section. Time limited, I may optimize it later):