基于C++的汉诺塔非递归实现 (PTA习题)
借助堆栈以非递归(循环)方式求解汉诺塔的问题(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<string>
#include<iostream>
#include<algorithm>
#include<stack>
using namespace std;
int main()
{
stack < int > a, b, c;
int i, j, n;
cin >> n;
char s[4] = { 'p','a','b','c' };
a.push(99999); b.push(999999); c.push(999999);
for (i = n; i >= 1; i--)
{
a.push(i);
}
if (n % 2 == 1)
{
s[2] = 'c';
s[3] = 'b';
}
for (i = 1;; i++)
{
if (i % 3 == 1)
{
cout << s[1] <<" -> "<< s[2] << "\n";
b.push(a.top());
a.pop();
if (b.size() == n + 1 || c.size() == n + 1)
break;
if (c.top() > a.top())
{
cout << s[1] << " -> " << s[3] << "\n";
c.push(a.top());
a.pop();
}
else
{
cout << s[3] << " -> " << s[1] << "\n";
a.push(c.top());
c.pop();
}
}
else if (i % 3 == 2)
{
cout << s[2] << " -> " << s[3] << "\n";
c.push(b.top());
b.pop();
if (b.size() == n + 1 || c.size() == n + 1)
break;
if (b.top() > a.top())
{
cout << s[1] << " -> " << s[2] << "\n";
b.push(a.top());
a.pop();
}
else
{
cout << s[2] << " -> " << s[1] << "\n";
a.push(b.top());
b.pop();
}
}
else
{
cout << s[3] << " -> " << s[1] << "\n";
a.push(c.top());
c.pop();
if (b.size() == n + 1 || c.size() == n + 1)
break;
if (c.top() > b.top())
{
cout << s[2] << " -> " << s[3] << "\n";
c.push(b.top());
b.pop();
}
else
{
cout << s[3] << " -> " << s[2] << "\n";
b.push(c.top());
c.pop();
}
i = 0;
}
}
}