Algorithm


Tower of Hanoi Algorithm:

  1. 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.
  2. If `n == 1`:
    • Move the disk from `source` to `target`.
    • Return.
  3. Recursively move `n-1` disks from `source` to `auxiliary` using `target` as the auxiliary rod.
  4. Move the nth disk from `source` to `target`.
  5. Recursively move `n-1` disks from `auxiliary` to `target` using `source` as the auxiliary rod.

Example:

For 3 disks:

  1. Move disk 1 from `source` to `target`.
  2. Move disk 2 from `source` to `auxiliary`.
  3. Move disk 1 from `target` to `auxiliary`.
  4. Move disk 3 from `source` to `target`.
  5. Move disk 1 from `auxiliary` to `source`.
  6. Move disk 2 from `auxiliary` to `target`.
  7. 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.