
Hanoi Problem
Hi Guys,
I have problem understanding the recursive approached used in solving
Towers of Hanoi problem given below(got it from google).
Can anyone explain me.
disks is the number of disks to be moved to the destination
void TowersOfHanoi(int disks, int from, int to, int spare) {
// Solve the problem of moving the number of disks specified
// by the first parameter from the stack specified by the
// second parameter to the stack specified by the third
// parameter. The stack specified by the fourth parameter
// is avaialable for use as a spare.
if (disks == 1) {
// There is only one disk to be moved. Just move it.
System.out.println("Move a disk from stack number "
+ from + " to stack number " + to);
}
else {
// Move all but one disk to the spare stack, then
// move the bottom disk, then put all the other
// disks on top of it.
TowersOfHanoi(disks1, from, spare, to);
System.out.println("Move a disk from stack number "
+ from + " to stack number " + to);
TowersOfHanoi(disks1, spare, to, from);
}
}
Thanks in advance