Translate

Labels

Thursday 13 June 2013

PROGRAM TO SOLVE TOWER OF HANOI PROBLEM

main()
{
int source,destination,other,nodisks;
printf("Enter the number of disks:\n");
scanf("%d",&nodisks);
if(nodisks<1)
{
printf("Illegal input\n");
exit(1);
}
source=1;
other=2;
destination=3;

hanoi(nodisks,source,other,destination);
}
hanoi(int nodisks,int source,int other,int destination)
{
if(nodisks)
{
hanoi(nodisks-1,source,destination,other);
move(nodisks,source,destination);
hanoi(nodisks-1,other,source,destination);
}
}
move(int nodisks,int source,int destination)
{
printf("Move disk%d from pole %d to pole %d \n",nodisks,source,destination);
}

OUTPUT:
Enter the number of disks:
3
Move disk 1 from pole 1 to pole 3
Move disk 2 from pole 1 to pole 2
Move disk 1 from pole 3 to pole 2
Move disk 3 from pole 1 to pole 3
Move disk 1 from pole 2 to pole 1
Move disk 2 from pole 2 to pole 3
Move disk 1 from pole 1 to pole 3

No comments: