Strange Towers of Hanoi
InterviewTime limit1sMemory limit128 MB
Compute the minimum number of moves to transfer n disks (n at most 12) from tower A to tower D using four towers.
- Level
Medium4 of 10
- Topics
- Dynamic programming, Recursion, Math, Brute force
- Solved
- No attempts yet
Problem
Charlie Darkbrown is sitting through yet another boring Computer Science lesson. Right now the teacher is explaining the standard Tower of Hanoi problem, which bores Charlie to death.

Figure: The standard (three) Towers of Hanoi.
The teacher points at the blackboard and says: "Here is the problem.
- There are three towers: A, B and C.
- There are disks. The number stays constant while solving the puzzle.
- All disks have different sizes.
- Initially the disks are stacked on tower A, increasing in size from the top to the bottom.
- The goal is to move all of the disks from tower A to tower C.
- One disk at a time may be moved from the top of a tower onto an empty tower, or onto a tower whose top disk is larger.
Your task is to compute the smallest number of moves needed to move every disk from tower A to tower C."
Charlie: "This is incredibly boring — everyone knows this can be solved with a simple recursion. I refuse to code something this trivial!"
The teacher sighs: "Fine, Charlie, let us find something harder for you. You get a fourth tower D. Compute the smallest number of moves needed to move all of the disks from tower A to tower D using all four towers."
Charlie looks annoyed: "Ugh... I do not know an optimal algorithm for four towers..."
The real trouble is that problem solving is not one of Charlie's strengths. The one thing Charlie is truly good at is sitting next to someone who can do the work — and you are that someone. He is already glaring at you.
Luckily you know that the following algorithm works for . First, disks are kept fixed on tower A and the remaining disks are moved from tower A to tower B using the four-tower algorithm. Then the disks on tower A are moved to tower D using the three-tower algorithm. Finally the disks on tower B are moved to tower D using the four-tower algorithm (without disturbing the disks already on tower D). Do this for every and take the value of that yields the fewest moves.
For example, with and you first move disk from tower A to tower B using the four-tower algorithm (one move), then move the remaining two disks from tower A to tower D using the three-tower algorithm (three moves), and finally move the single disk from tower B to tower D using the four-tower algorithm (one more move). So with costs moves. Checking the other values and confirms that is indeed optimal.
Input
A single line containing one integer (), the number of disks.
Output
Print a single line containing the minimum number of moves needed to move all disks from tower A to tower D using all four towers.