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
- Ch3-4: solve Hanoi in C++ with recursion, and with stack explicitly
- Learning with python: Chapter3~4 Functions,Conditionals and Recursion
- Ch3-2: implement min() for a stack with O(1)
- [C++]Stack with Template
- Debugging tombstones with ndk-stack and addr2line
- Debugging tombstones with ndk-stack and addr2line
- Selection Sort with stack and queue
- Insertion Sort with queue and stack
- update with case and in
- Your app, extension, and/or linked framework appears to contain code designed explicitly with the ca
- How to deal with Whitespaces in scanf, gets(in C) and cin, getline(in C++) ?
- Ch3-5: implement myqueue with 2 stacks
- C program for stack with array implementation
- C : stack memory, goto and “jump into scope of identifier with variably modified type”,
- C/C++---C and CXX compiler with c or cpp in struct
- Out With the Old and in With the New
- Image store in SQL-Server 2005 database and retrieve it in asp.net application with C#:
- Generating and working with GUIDs in .NET
- 和回忆擦肩,我们要做的就是不回头勇敢向前
- 2014.01.14解题报告
- CentOS 设置网卡开机启动、启动网卡、设置网卡参数
- 微信模板消息,逼运营商上梁山
- 4、Maven安装最佳实践
- Ch3-4: solve Hanoi in C++ with recursion, and with stack explicitly
- Hibernate搭建
- node.js 初体验
- Ubuntu12.04 安装Nvidia显卡驱动
- C++在VC6中非CWnd类中怎样设置SetTimer及其回调函数?
- XCode调试技巧–设置全局断点快速定位问题代码所在行
- 据传Facebook本月底可能推类Flipboard的新闻聚合阅读器,命名Paper
- Beyond Compare 3在windows和linux下实现提取增量包
- UDK 坦克初步实现