Google+ Program For Tower of Hanoi in C[How to] - CodieeHome
“Any fool can write code that a computer can understand. Good programmers write code that humans can understand.”
__

Tower of Hanoi

Goal:- Program for tower of Hanoi in c.

Method-Used:- Recursion

Explanation:- The tower of Hanoi is a Mathematical Puzzle and also known as Brahma tower. In this problem we have  three rods and no of plates on one of them in ascending order of size. 

Main task is to move all the plates on another rode in same order(ascending order of size) with following three rules:

  1. We can move only  one Plate at a time.
  2. We can take the upper plate of any rod and only place it on top of another rod.
  3. A plate cannot be put on a smaller plate.
There are  many ways to solve this problem :-

  • Iterative Solution.
  • Recursive Solution.
  • Non-Recursive Solution.
  • Binary Solution.
  • Gray-Code Solution.
Program is given below implements the recursive solution ,if you want to read about other solutions then search on Wikipedia.

Recursive Solution:- Suppose we have three rods named as peg 1,peg 2,peg 3 and have n plates on peg 1. If we want to move all plates from peg 1 to peg 3 then procedure is:-(With Hanoi rules)

  1. If n>1 then n-1 smaller plates from peg 1 to peg 2.
  2. Move largest plate to peg 3.
  3. If n>1 then move n-1 smaller plates from peg 2 to peg 1.
  4. Move second largest plate to peg 3.
  5. if n>1 then go to step 1. 
Animated Solution:-



Program:-

/* HANOI.C */

#include<stdio.h>

#include<conio.h>

void hanoi_tower(char peg1, char peg2, char  peg3, int n) // Hanoi Function

{

      if( n <= 0)

                printf("\n\t Illegal entry ");

     if(n == 1)

               printf("\n \n\t\tMove Disk from %c to %c", peg1, peg3);

     else

        {

                hanoi_tower(peg1, peg3, peg2, n-1);

hanoi_tower(peg1, peg2, peg3, 1);

hanoi_tower(peg2, peg1, peg3, n-1);

}

}

/* main function */

int main()

{

         int num_of_disks;

printf("\n Input the number of disc: ");

scanf("%d", &num_of_disks);

printf("\n Tower of Hanoi for %d DISC", num_of_disks);

hanoi_tower('X', 'Y', 'Z', num_of_disks);

getch();

}

Output:-


If you want to share more information about topic discussed above or find anything incorrect Please do comments.  

0 comments:

Post a Comment

 
Top