Technical Article => Programming => Algorithm

# Implementation of Tower of Hanoi

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.

### RELATED

### 0 COMMENT

No comment for this article.

## Next is here |

By sonic0002 |

This is an advertisement at a crossing in Mid East. The two big smartphone manufacturers are tying their best to promote their products. Apparently Huawei is winning this ad battle.
Here is the next one of this series of advertisements of these two companies. This really shows the art of advertising |