汉诺塔算法
来源:互联网 发布:收据软件 编辑:程序博客网 时间:2024/06/03 15:47
/** Hanoi思路:用递归//栈*假设开始柱子:A,中间柱子:B,目标柱子:C*第一步:将n-1个盘子从A借助C移到B*第二步:将第n个盘子从A到C*第三步:将n-1个盘子从B借助A移到C**///递归算法:#include <iostream>#include<stdio.h>using namespace std;void Hanoi(int plate, char A,char B,char C);static int count;//计算移动的总次数int main(){ int plate; while(cin>>plate) { getchar(); char start; char depend; char destination; scanf("%c%*c%c%*c%c%*c",&start,&depend,&destination);//输入起始柱,中间柱和目标柱 count=0; Hanoi(plate,start,depend,destination); cout<<endl; } return 0;}void Hanoi(int plate, char A,char B,char C){ if(plate==1) { cout<<"第"<<++count<<"次:"; cout<<"第"<<plate<<"个盘子从"<<A<<"移到"<<C<<endl; } else { Hanoi(plate-1,A,C,B);//将n-1个从 A借助 C 移到 B cout<<"第"<<++count<<"次:"; cout<<"第"<<plate<<"个盘子从"<<A<<"移到"<<C<<endl;//将最底下的最大盘子从A移到C Hanoi(plate-1,B,A,C);//将B上的n-1个盘子由B借助A移到C }}//栈#include<iostream>#include<stack>#include<stdio.h>using namespace std;struct EveryTime//每次移动{ int CurPlateNum; char start; char dependent; char destination; EveryTime(){} EveryTime(int n, char A, char B, char C):CurPlateNum(n),start(A),dependent(B),destination(C){}};int main(){ stack<EveryTime> stk; EveryTime cur; int n; int count;//统计需要移动的次数 while(cin>>n) { getchar(); char start; char depend; char destination; scanf("%c%*c%c%*c%c%*c",&start,&depend,&destination);//输入起始柱,中间柱和目标柱 count=0; stk.push(EveryTime(n,start,depend,destination)); while(!stk.empty()) { cur=stk.top();//用cur保存栈顶,下面用cur进行讨论 stk.pop();//弹出栈顶 if(cur.CurPlateNum==1) { cout<<"第"<<++count<<"次:"; cout<<"第"<<cur.CurPlateNum<<"个盘子从"<<cur.start<<"移到"<<cur.destination<<endl; } else//根据栈先进后出特点应该将顺序倒过来.因为递归可以独立进行,而栈先进去的元素等会晚执行 { stk.push(EveryTime(cur.CurPlateNum-1,cur.dependent,cur.start,cur.destination));//将n-1个从B(dependent)借助A(start)移到C(destination) stk.push(EveryTime(1,cur.start,cur.dependent,cur.destination));//将第n个由A(start)移到C(destination) stk.push(EveryTime(cur.CurPlateNum-1,cur.start,cur.destination,cur.dependent));//将n-1个从A(start)借助C(destination)移到B(depenent) } } } return 0;}
阅读全文
0 0
- 汉诺塔算法
- “汉诺塔”算法
- 汉诺塔算法
- 汉诺塔算法
- 汉诺塔算法
- 汉诺塔算法
- 汉诺塔算法
- 【算法】汉诺塔
- 汉诺塔算法
- 汉诺塔-算法
- 汉诺塔算法
- 汉诺塔算法
- 汉诺塔算法
- 汉诺塔算法
- 汉诺塔 算法
- 汉诺塔算法
- 汉诺塔算法
- 汉诺塔算法
- redis 事务的特性
- 开源IoT 平台Kaa 安装 (CentOS 7 )
- 快捷键_NodePad++
- 操作系统总结
- Cisco CLI下输入问号“?”
- 汉诺塔算法
- 自定义vscode插件安装位置
- 快捷键_Idea
- Mysql存储引擎
- C++的学习笔记(第五章:函数)
- 集合总结
- 常用_Linux命令
- StringUtils工具类对于字符串是否为空的校验
- 第四章 ALDS1_3_B:Queue 队列