The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules:
- Only one disk can be moved at a time.
- Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack.
- No disk may be placed on top of a smaller disk.
Towers of Honai solution , source:wikipedia |
public class TowersOfHanoi {
/** Main method */
public static void main(String[] args) {
// Create a Scanner
Scanner input = new Scanner(System.in);
System.out.print("Enter number of disks: ");
int n = input.nextInt();
// Find the solution recursively
System.out.println("The moves are:");
moveDisks(n, 'A', 'B', 'C');
}
/** The method for finding the solution to move n disks
from fromTower to toTower with auxTower */
public static void moveDisks(int n, char fromTower,char toTower, char auxTower)
{
if (n == 1) // Stopping condition
System.out.println("Move disk " + n + " from " +
fromTower + " to " + toTower);
else {
moveDisks(n - 1, fromTower, auxTower, toTower);
System.out.println("Move disk " + n + " from " +
fromTower + " to " + toTower);
moveDisks(n - 1, auxTower, toTower, fromTower);
}
}
}
I have read your blog its very attractive and impressive. I like it your blog.
ReplyDeleteJava Training in Chennai Core Java Training in Chennai Core Java Training in Chennai
Java Online Training Java Online Training JavaEE Training in Chennai Java EE Training in Chennai