1-2 汉诺塔的非递归实现 (25 分)
借助堆栈以非递归(循环)方式求解汉诺塔的问题(n, a, b, c),即将N个盘子从起始柱(标记为“a”)通过借助柱(标记为“b”)移动到目标柱(标记为“c”),并保证每个移动符合汉诺塔问题的要求。
输入格式:
输入为一个正整数N,即起始柱上的盘数。
输出格式:
每个操作(移动)占一行,按柱1 -> 柱2
的格式输出。
输入样例:
3
结尾无空行
输出样例:
a -> c
a -> b
c -> b
a -> c
b -> a
b -> c
a -> c结尾无空行
代码:
#include <stack>
#include <iostream>
using namespace std;
struct node
{
int n, a, b, c;
node(int m, int x, int y, int z) : n(m), a(x), b(y), c(z) {}
};
int main()
{
int n;
cin >> n;
stack<node> s;
s.push(node(n, 'a', 'b', 'c'));
while (!s.empty())
{
node t = s.top();
s.pop();
if (t.n == 1)
printf("%c -> %c\n", t.a, t.c);
else
{
s.push(node(t.n - 1, t.b, t.a, t.c));
s.push(node(1, t.a, t.b, t.c));
s.push(node(t.n - 1, t.a, t.c, t.b));
}
}
}