Today's Question:  What weekend projects have you created?        GIVE A SHOUT

Technical Article => Programming =>  Algorithm

Implementation of Tower of Hanoi

  Peter      2012-08-20 02:15:55      2,270    0

The Tower of Hanoi is a mathematical game or puzzle. It consists of three rods, and a number of disks of different sizes which can slide onto any rod. The puzzle starts with the disks in a neat stack in ascending order of size on one rod, the smallest at the top, thus making a conical shape.

The objective of the puzzle is to move the entire stack to another rod, obeying the following rules:

  • Only one disk may be moved at a time.
  • Each move consists of taking the upper disk from one of the rods and sliding it onto another rod, on top of the other disks that may already be present on that rod.
  • No disk may be placed on top of a smaller disk.

From the puzzle description, we can see that it is actually is an recursive question, to move the biggest disk to the final rod, we must first move all the disks smaller than the biggest disk to the mid rod. For all the rest disks, the same steps need to be followed.

Here is an implementation of this puzzle:

#include <iostream>
#include <string>

using namespace std;

void move(char begin,char mid,char end,int i){
        cout<<"Move "<<i<<" from "<<begin<<" to "<<end<<endl;
        cout<<"Move "<<i<<" from "<<begin<<" to "<<end<<endl;
int main(){
    int n=3;
    return 0;

In move(), if only one disk is present, then directly move the disk from begin to end. Otherwise, we move the (i-1) disks from begin to mid first, then we move the ith disk from begin to end. Finally, we move the (i-1) disks from mid to end.



Share on Facebook  Share on Twitter  Share on Google+  Share on Weibo  Share on Reddit  Share on Digg  Share on Tumblr    Delicious



No comment for this article.


Real life of programmer

By sonic0002