|
|
|
Example:
|
Try out the moves with this applet: click here
|
In other words:
|
|
public static String hanoi( int nDisks, int fromPeg, int toPeg )
{
....
}
|
The meaning of the input parameters are:
|
|
Here are the general step to write a recursive algorithm - summarized for your convenience:
|
|
|
|
|
String hanoi( int nDisks, int fromPeg, int toPeg )
{
int helpPeg;
if ( nDisks == 1 )
{
/* ------------------------------------------------------
Solving a trivial (base case) Tower of Hanoi problem:
|
public class Recurse3
{
public static String hanoi(int nDisks, int fromPeg, int toPeg)
{
int helpPeg;
String Sol1, Sol2, MyStep, mySol; // Contains moves
if ( nDisks == 1 )
{
return fromPeg + " -> " + toPeg + "\n";
}
else
{
helpPeg = 6 - fromPeg - toPeg; // Because fromPeg + helpPeg + toPeg = 6
Sol1 = hanoi(nDisks-1, fromPeg, helpPeg);
MyStep = fromPeg + " -> " + toPeg + "\n";
Sol2 = hanoi(nDisks-1, helpPeg, toPeg);
mySol = Sol1 + MyStep + Sol2; // + = String concatenation !
return mySol;;
}
}
|
How to run the program:
|
hanoi( 4, 1, 3 ) --- move 4 disks from peg 1 ⇒ peg 3
|
According to the hanoi() method:
public static String hanoi(int nDisks, int fromPeg, int toPeg)
{
int helpPeg;
String Sol1, Sol2, MyStep, mySol; // Contains moves
if ( nDisks == 1 )
{
return fromPeg + " -> " + toPeg + "\n";
}
else
{
helpPeg = 6 - fromPeg - toPeg; // Because fromPeg + helpPeg + toPeg = 6
Sol1 = hanoi(nDisks-1, fromPeg, helpPeg);
MyStep = fromPeg + " -> " + toPeg + "\n";
Sol2 = hanoi(nDisks-1, helpPeg, toPeg);
mySol = Sol1 + MyStep + Sol2; // + = String concatenation !
return mySol;;
}
}
|
the invocation will execute these statements:
helpPeg = 6 - 1 - 3 = 2; Sol1 = hanoi( 3, 1, 2 ); // Move 3 disks from peg 1 ⇒ peg 2 MyStep = "1 -> 3"; Sol2 = hanoi( 3, 2, 3 ); // Move 3 disks from peg 2 ⇒ peg 3 mySol = Sol1 + MyStep + Sol2; return mySol; |
Output of hanoi(4,1,3):
1 -> 2
1 -> 3
2 -> 3
1 -> 2 (These are steps in Sol1 !!!)
3 -> 1
3 -> 2
1 -> 2
1 -> 3 (this is MyStep !!!)
2 -> 3
2 -> 1
3 -> 1
2 -> 3 (These are steps in Sol2 !!!)
1 -> 2
1 -> 3
2 -> 3
|
|