1 Star 0 Fork 0

Kaiyu Shen/Hannoi

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
hannoi.cpp 1.60 KB
一键复制 编辑 原始数据 按行查看 历史
Kaiyu Shen 提交于 2023-03-31 17:31 . update README
#include <cstdio>
#include <stack>
using namespace std;
class Tower {
private:
int _n; // numbers of hannoi
int _N; // numbers of times
void _Hannoi(int n, int from, int to) {
int mi;
for (int i = 0; i < 3; i++) {
if (from != i && to != i) mi = i;
}
if (n == 0) return;
if (n == 1) {
_move(from, to);
}
else {
_Hannoi(n - 1, from, mi);
_move(from, to);
_Hannoi(n - 1, mi, to);
}
}
void _move(int from, int to) {
towers[to].push(towers[from].top());
towers[from].pop();
++times;
}
public:
stack<int> *towers = new stack<int>[3];
int times;
Tower(int n = 3) {
_n = n;
_N = 2^n - 1;
times = 0;
for (int i = _n - 1; 0 <= i; i--) towers[0].push(i);
}
void Hannoi() {_Hannoi(_n, 0, 2);}
void showTowers() {
stack<int> *twrs = new stack<int>[3];
printf("Towers[size=%d times=%d]:\n", _n, times);
for (int i = 0; i < 3; i++) {
twrs[i] = towers[i];
printf("[%d]\t", i);
while (!twrs[i].empty()) {
printf("%d ", twrs[i].top());
twrs[i].pop();
}
printf("\n");
}
printf("\n");
delete [] twrs;
}
~Tower() { delete [] towers; }
};
int main() {
int n;
printf("请输入塔数:");
scanf("%d", &n);
if (n <= 0) {
printf("你这是什么意思?\n");
return 0;
}
Tower T(n);
T.showTowers();
T.Hannoi();
T.showTowers();
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C++
1
https://gitee.com/kyshen/hannoi.git
git@gitee.com:kyshen/hannoi.git
kyshen
hannoi
Hannoi
master

搜索帮助

0d507c66 1850385 C8b1a773 1850385