(算法)Hanoi Problem汉诺塔问题
算法 Problem 汉诺塔 问题
2023-09-14 08:59:06 时间
Problem:
There are three poles and N disks where each disk is heaver than the next disk. In the initial conguration, the discs are stacked upon another on the first pole where the lighter discs are above the heavier discs. We want to move all the discs to the last pole with the following conditions:
- Only one disc can be moved from one pole to another at a time.
- The discs have to be stacked such that all the lighter discs are on top of the heavier ones.
Recursion:
To move N discs from the first pole to the last pole, we need to move N-1 discs to the middle pole, then move the Nth disc to the last pole, and then move all N-1 discs from the middle pole back to the last pole.
Code:
#include <iostream> using namespace std; void hanoi(int N,int start,int helper,int destination){ if(N==1) cout<<"Move "<<start<<" to "<<destination<<endl; else{ hanoi(N-1,start,destination,helper); hanoi(1,start,helper,destination); hanoi(N-1,helper,start,destination); } } int main() { int N=10; hanoi(10,1,2,3); return 0; }
相关文章
- 经典的7种排序算法 原理C++实现
- java实现 蓝桥杯 算法提高 Problem S4: Interesting Numbers 加强版
- 八大排序算法总结
- (算法)位图BitMap
- 【算法】算法复杂度分析初步
- 【STM32F429开发板用户手册】第47章 STM32F429的SPI 总线应用之SPI Flash的MDK下载算法制作
- 蚂蚁群算法求解最短路径问题(Python&Matlab实现)
- 【智能算法】粒子群算法求解出最大值问题
- 【阶段三】Python机器学习32篇:机器学习项目实战:关联分析的基本概念和Apriori算法的数学演示
- 关于KNN算法的新理解新运用
- 最小生成树----prim算法----普利姆算法
- 小朋友的游戏(训练排序算法)
- 数据结构和算法 布隆过滤器示例