Implementation of Tower of Hanoi

  Peter        2012-08-20 02:15:55       3,407        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){
    if(i==1){
        cout<<"Move "<<i<<" from "<<begin<<" to "<<end<<endl;
    }else{
        move(begin,end,mid,i-1);
        cout<<"Move "<<i<<" from "<<begin<<" to "<<end<<endl;
        move(mid,begin,end,i-1);
    }
}
 
int main(){
    int n=3;
    
    move('A','B','C',n);
    
    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.

ALGORITHM  TOWER OF HANOI 

       

  RELATED


  0 COMMENT


No comment for this article.



  RANDOM FUN

Emoji of the richest person in China -- Jack Ma