Recursive algorithm 3: Hanoi Tower

Problem description

Move rule:

Only one disc can be moved at a time;

The disc can be inserted on any of the towers a, B and C;

At no time can a larger disc be pressed against a smaller disc.

Analysis

boundary condition

When there is only one ring, just move the ring from the first tower to the third tower

Recursive condition

1. Move n-1 ring from the first tower to the second tower, with the third tower as an auxiliary

2. Move the nth ring from the first tower to the third tower

3. Move n-1 ring from the second tower to the third tower, with the first tower as an auxiliary

Code

## Recursive implementation of simple Hanoi Tower

```
#include<iostream>
using namespace std;
void move(char from, char to){
cout<<"Move"<<from<<"to"<<to<<endl;
}
void hanoi(int n, char first, char second, char third){
if(n==1){
move(first, third);
}else{
hanoi(n-1, first, third, second);
move(first, third);
hanoi(n-1, second, first, third);
}
}
int main(){
int m;
cout<<"the number of diskes:";
cin>>m;
cout<<"move "<<m<<" diskes:\n";
hanoi(m,'A','B','C');
return 0;
}
```

## Hanoi Tower recursive implementation

```
#include<iostream>
using namespace std;
int main(){
int m;
cin>>m;
long long p = 0;
for(int i=0; i<m; i++){
p=2*p+1;
}
cout<<2*p<<endl;
return 0;
}
```