Ch3-4: solve Hanoi in C++ with recursion, and with stack explicitly

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



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值