Algorithm
Tower of Hanoi Algorithm:
- Define a recursive function `TowerOfHanoi(n, source, target, auxiliary)` where:
- `n` is the number of disks.
- `source` is the rod where the disks are initially placed.
- `target` is the rod where the disks need to be moved.
- `auxiliary` is the intermediate rod used during the process.
- If `n == 1`:
- Move the disk from `source` to `target`.
- Return.
- Recursively move `n-1` disks from `source` to `auxiliary` using `target` as the auxiliary rod.
- Move the nth disk from `source` to `target`.
- Recursively move `n-1` disks from `auxiliary` to `target` using `source` as the auxiliary rod.
Example:
For 3 disks:
- Move disk 1 from `source` to `target`.
- Move disk 2 from `source` to `auxiliary`.
- Move disk 1 from `target` to `auxiliary`.
- Move disk 3 from `source` to `target`.
- Move disk 1 from `auxiliary` to `source`.
- Move disk 2 from `auxiliary` to `target`.
- Move disk 1 from `source` to `target`.
Note: The Tower of Hanoi problem simulationnstrates the power of recursion and is often used as a teaching tool for recursive algorithms.