- Only one disk can be taken at a time.
- It is not allowed to take any disk other the topmost one from a tower.
- Never place a larger disk on top of a smaller one.
- Place a disk nowhere else other than on tower.
The java program here displays the optimal solution for towers of Hanoi problem. You can enter the number of disks when you start. The program lists an optimal number of moves to solve the tower of Hanoi puzzle. The solution is always optimal. For a 3 disks puzzle, the optiomal number of moves is 7. This c program uses a recursive function to find the solution of tower of Hanoi puzzle. The program is as follows.
import java.util.Scanner; public class Hanoi{ static void moveTopN(int n, int a, int b, int c) //to Move top n disk from tower a to tower c //Uses tower b for swapping { if(n>=1) { moveTopN(n-1,a,c,b); System.out.printf("\nMove top disk from tower %d to tower %d",a,c); moveTopN(n-1,b,a,c); } } public static void main(String[] args) { int n; System.out.printf("Enter number of disks"); Scanner sc=new Scanner(System.in); n=sc.nextInt(); moveTopN(n,1,2,3); } }
No comments:
Post a Comment