- 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 c 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 program displays all the moves in the order. The solution is always optimal. For a 3 disks puzzle, the optimal 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.
#include<stdio.h> 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); printf("\nMove top disk from tower %d to tower %d",a,c); moveTopN(n-1,b,a,c); } } void main() { int n; printf("Enter number of disks"); scanf("%d",&n); moveTopN(n,1,2,3); }The above c program first reads the number of disks in the tower of Hanoi Puzzle. Then it displays the optimal moves to solve the puzzle.
No comments:
Post a Comment