Implement Tower of Hanoi Problem using C programmg with algorithm.
Tower of Hanoi problem:
Initial state:
Conditions:
Initial state:
-
There are three poles named as origin, intermediate and destination.
-
n number of different-sized disks having hole at the center is stacked around the
origin pole in decreasing order.
-
The disks are numbered as 1, 2, 3, 4, ...................,n.
Objective:
Conditions:
-
Move only one disk at a time.
-
Each disk must always be placed around one of the pole.
-
Never place larger disk on top of smaller disk.
Algorithm: - To move a tower of n disks from source to dest (where n is positive integer):
1. If n ===1:
1.1. Move a single disk from source to dest.
2. If n > 1:
2.1. Let temp be the remaining pole other than source and dest.
2.2. Move a tower of (n – 1) disks form source to temp. 2.3. Move a single disk from source to dest.
2.4. Move a tower of (n – 1) disks form temp to dest.
3. Terminate.
Example: Recursive solution of tower of Hanoi:
#include <stdio.h>
#include <conio.h>
void TOH(int, char, char, char); //Function prototype void main()
{
int n;
printf(“Enter number of disks”); scanf(“%d”,&n); TOH(n,’O’,’D’,’I’);
getch();
}
void TOH(int n, char A, char B, char C) {
if(n>0) {
TOH(n-1, A, C, B);
Printf(“Move disk %d from %c to%c\n”, n, A, B); TOH(n-1, C, B, A);
} }
0 comments:
Feel free to contact the admin for any suggestions and help.