题目链接
关键点:
1、转换汉诺塔递归的思想,利用堆栈将其倒过来
递归:先将n-1个块从a借助c移到b,再将a上的一个块直接移到c,最后将b上的n-1个块借助a移到c
完整代码:
# include <bits/stdc++.h>
using namespace std;
struct ty{
int n;
char a, b, c;
};
typedef struct ty node;
stack<ty>s;
int n;
node t, x, now;
int main()
{
scanf("%d", &n);
x.a = 'a', x.b = 'b', x.c = 'c';
x.n = n;
s.push(x);
while (!s.empty())
{
t = s.top();
// cout<<t.a<<" "<<t.b<<" "<<t.c<<" "<<endl;
s.pop();
if (t.n == 1)
{
printf("%c -> %c\n", t.a, t.c);
}
else
{
now.a = t.b, now.b = t.a, now.c = t.c, now.n=t.n-1;
s.push(now);
now.a = t.a, now.b = t.b, now.c = t.c, now.n = 1;
s.push(now);
now.a = t.a, now.b = t.c, now.c = t.b, now.n=t.n-1;
s.push(now);
}
}
return 0;
}