10.2. Tower of Hanoi

This section discusses recursive and dynamic programming ways of solving the Tower of Hanoi problem.

The followings demonstrate the Tower of Hanoi problem:

Abstraction

Let us create the abstract class Hanoi:

  • L9: returns a list of movements to solve the given problem.

    • n: the total number of rings.

    • source: the ID of the source tower.

    • intermediate: the ID of the intermediate tower.

    • destination: the ID of the destination tower.

  • L11: returns the string representation of a movement.

Recursion

Let us create the HanoiRecursive class inheriting Hanoi:

Dynamic Programming

Let us create the HanoiDynamic class inheriting Hanoi:

Benchmark

The followings show performance comparison:

Last updated

Was this helpful?