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

来源:互联网 发布:windows xp 更新 编辑:程序博客网 时间:2024/06/06 12:56

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 yuxiaolin1023 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!


output:
Executing the program....$demo move disk: 1from A to Cmove disk: 2from A to Bmove disk: 1from C to Bmove disk: 3from A to Cmove disk: 1from B to Amove disk: 2from B to Cmove disk: 1from A to C



0 0
原创粉丝点击