Hanoi has these conditions:
3 rods, N disks, initially N disks are ascendingly from top to down in 1st rod.
Objective: move all N disks to the 3rd rod.
It must follow these 3 laws:
1. every time only move one disk;
2. only move the upper disk;
3. only put small disk on larger disk.
递归可以很优雅的解决这个问题,而这也是递归最长用到的实例:
#include <iostream>
#include <cmath>
using namespace std;
int cishu;
void hanoi(int n, char src, char bri, char dst){
if(n==1){
//cout<<"Move disk "<<n<<" from "<<src<<" to "<<dst<<endl;
++cishu;
}
else{
hanoi(n-1, src, dst, bri); //++cishu;
//cout<<"Move disk "<<n<<" from "<<src<<" to "<<dst<<endl;
hanoi(n-1, bri, src, dst); ++cishu;
}
}
int main(){
int n = 10;
cishu = 0;
hanoi(n, 'A', 'B', 'C');
cout << "done yuxiaolin" << endl;
cout << cishu << " and calc result = " << pow(2,n)-1;
return 0;
}
结果:
Executing the program....
$demo
done yuxiaolin
1023 and calc result = 1023
FOLLOW UP: use stack
当然,题目的follow up是显式的应用stack, 其实recursive就是用的stack,不过是compiler自动生成。就如同个3-2里面说的:array或者arraylist就是pointer In C++。This solution needs a while to fully understand and also very IMPORTANT!
// 3-4: follow up solution, use stack.
// check http://hawstein.com/posts/3.4.html for fully explaination Very clear!
#include
#include
using namespace std;
struct op{
int begin, end;
char src, bri, des;
op(){}
op(int opbegin, int opend, int opsrc, int opbri, int opdes):
begin(opbegin), end(opend), src(opsrc), bri(opbri), des(opdes){
}
};
void hanoi(int n, char src, char bri, char des){
stack
st;
op tmp;
st.push(op(1,n,src, bri, des));
while(!st.empty()){ // if use ~, will cause segemntation fault
tmp = st.top();
st.pop();
if(tmp.begin!=tmp.end){
st.push(op(tmp.begin, tmp.end-1, tmp.bri, tmp.src, tmp.des));
st.push(op(tmp.end, tmp.end, tmp.src, tmp.bri, tmp.des));
st.push(op(tmp.begin, tmp.end-1, tmp.src, tmp.des, tmp.bri));
// reversed order
}
else
cout << "move disk: "<< tmp.begin << "from "<< tmp.src << " to " << tmp.des<
output:
Executing the program....
$demo
move disk: 1from A to C
move disk: 2from A to B
move disk: 1from C to B
move disk: 3from A to C
move disk: 1from B to A
move disk: 2from B to C
move disk: 1from A to C