I'm trying to resolve Tower of Hanoi problem; I wrote this code:
public class TowersOfHanoi {
public static void main(String[] args) {
move(5, 1, 3);
}
public static void move(int disks, int from, int to) {
if (disks > 0) {
int other = 6 - from - to; // sum of index 1+2+3=6
System.out.println("Move disk from peg " + from + " to " + to);
move(disks - 1, from, other);
move(disks - 1, other, to);
}
}
}
but the result is wrong. The solution in my book is
public class TowersOfHanoi {
public static void main(String[] args) {
move(5, 1, 3);
}
public static void move(int disks, int from, int to) {
if (disks > 0) {
int other = 6 - from - to; // sum of index 1+2+3=6
move(disks - 1, from, other);
System.out.println("Move disk from peg " + from + " to " + to);
move(disks - 1, other, to);
}
}
}
why is this? I can't understand the ORDER of these expression:
- first it run
System.out.println()
- then it run
move(disks - 1, from, other)
- now it run
System.out.println()
again or runmove(disks - 1, other, to)
?
and WHEN RESTART the block code? Thanx.
The tower of hanoi works in a way that -:
The book solution is correct in. Your solution is wrong because you have moved the last disk in the beginning, this is against rule of tower of hanoi. I hope you get it.
A bit more elegant and understandable code after some modification where it works for any arbitary n. (Atleast for small values of n due to it exponential complexity)