Loading...
Loading...
A toy has three rods A, B and C. Rod A holds n discs, the largest at the bottom and the smallest (disc 1) on top. Move all discs to rod C. Only one disc moves at a time, and a disc may never sit on a smaller one.
Write a recursive method static long hanoi(int n, char from, char to, char via) that prints every move and returns how many moves it made. Print the total at the end.
Move disc d from X to Y, in order. Then a last line Total moves: k.Example 1
Input
1
Output
Move disc 1 from A to C Total moves: 1
One disc goes straight from A to C.
Example 2
Input
2
Output
Move disc 1 from A to B Move disc 2 from A to C Move disc 1 from B to C Total moves: 3
The small disc steps aside to B, the big one goes to C, the small one follows.
Try the problem first. Open one hint at a time.
To move n discs from from to to: first move the top n - 1 discs to via, then move disc n to to, then move the n - 1 discs from via to to.
The base case is n = 0: nothing to move, return 0.
The number of moves is (moves of the first call) + 1 + (moves of the second call).
Write your Java code, run it on the examples and submit it to hidden tests.
Solve in the editor