Towers of the Hanoi in Java


In the classic problem of the Towers of Hanoi, you have 3 towers and N discs of different sizes which can slide onto any tower.

How to Solve

First we think about sliding nth disc onto another tower. This handling is composed by the following steps.

  1. move (n-1)th disc from Tower1 to Tower2
  2. move nth disc from Tower1 to Tower3
  3. move (n-1)th disc from Tower2 to Tower3

From the above, we can move discs from Tower1 to Tower3. This idea can be executed by recursive.

Implementing the tower by stack

we can express the tower by using stack. The feature of Towers of the Hanoi is that I can only put disc onto larger disc than putting disc and I can not insert desc into middle of the discs. So, it is good to use stack.

Source Code