非递归汉诺塔问题
#include <bits/stdc++.h>
using namespace std;
struct _move {
int n;
int u;
char s, m, d;
_move(int n1, int u1, char s1, char m1, char d1) : n(n1), u(u1), s(s1), m(m1), d(d1) {
}
};
void honoi(int n, char a, char b, char c)
{
if (n <= 0)
return;
stack<_move> _stk;
_stk.push(_move(n, n - 1, a, b, c));
while (!_stk.empty()) {
_move m = _stk.top();
_stk.pop();
if (m.u == 0)
printf("%c -> %c\n", m.s, m.d);
else {
_stk.push(_move(m.n - 1, m.u - 1, m.m, m.s, m.d));
_stk.push(_move(m.n, 0, m.s, m.m, m.d));
_stk.push(_move(m.n - 1, m.u - 1, m.s, m.d, m.m));
}
}
}
int main() {
#ifndef ONLINE_JUDGE
freopen("D:/VS CODE/C++/in.txt", "r", stdin);
freopen("D:/VS CODE/C++/out.txt", "w", stdout);
#endif
int n;
cin >> n;
honoi(n, 'a', 'b', 'c');
fclose(stdin);
fclose(stdout);
return 0;
}