Prashnikaप्रश्निका
Code
About

Tower of Hanoi visualiser

Move a tower of discs from peg A to peg C, using B, one disc at a time and never a bigger disc on a smaller one. Press Play and watch the discs move while the recursive calls build up on the call stack and in the tree. A tower of n discs always takes 2n − 1 moves.

How to use it

  1. 1Type the number of discs (1 to 5), or tap an example.
  2. 2Press Show me, then Play. The discs move between the pegs A, B and C one step at a time.
  3. 3Watch the recursive calls on the call stack and in the tree, and the list of moves growing.

The animation needs JavaScript. Every step is written out below.

Result

Result
3 moves (2^2 - 1 = 3)
Every step in words (12 steps)
  1. hanoi(2, A, C) is called: move 2 discs from A to C using B.
  2. n = 2, not 1. First move the top 1 disc out of the way (from A to B, using C).
  3. hanoi(2, A, C) calls hanoi(1, A, B): it will clear the way.
  4. n = 1: the base case. Just move the one disc.
  5. Move disc 1 from A to B (move 1).
  6. Return. The frame leaves the stack.
  7. Move disc 2 from A to C (move 2).
  8. hanoi(2, A, C) calls hanoi(1, B, C): it puts the smaller discs back on top.
  9. n = 1: the base case. Just move the one disc.
  10. Move disc 1 from B to C (move 3).
  11. Return. The frame leaves the stack.
  12. hanoi(2, A, C) has moved 2 discs from A to C. It returns.
Start again

About the Tower of Hanoi visualiser

What it does

Solves the Tower of Hanoi for the number of discs you give: all the discs start on peg A and must end on peg C, using peg B, moving one disc at a time and never putting a bigger disc on a smaller one. The recursive method does it in three parts: move the top n − 1 discs to the spare peg, move the biggest disc, then move the n − 1 discs on top of it. The page shows the discs, the call stack, the call tree and the Java code together.

The number of moves

n discs always take 2n − 1 moves: 1, 3, 7, 15 and 31 moves for 1 to 5 discs. The number of moves is written under the answer.

Common questions

How many moves does the Tower of Hanoi need?

2n − 1 for n discs, and no fewer: 3 moves for 2 discs, 7 for 3, 15 for 4 and 31 for 5.

What is the recursive idea behind the Tower of Hanoi?

To move n discs from A to C using B, first move n − 1 discs from A to B using C, then move the biggest disc from A to C, then move the n − 1 discs from B to C using A. The base case is a single disc, which is moved directly.

Why only up to 5 discs?

The number of moves doubles with every disc, so a larger tower would be too long to follow on a page. Five discs already make 31 moves and 31 calls.

Can I see the code in Python, JavaScript or C++?

Yes. Choose the language in the menu above the code. Only the listing changes: the steps are always worked out from the Java program that ISC uses, and the highlighted line moves to the matching line of the language you chose.

More Computer Science tools

All study tools →