《CTCI》 P140
3 栈与队列
题目
3.4 In the classic problem of the Towers of Hanoi, you have 3 towers and N disks of different sizes which can slide onto any tower. The puzzle starts with disks sorted in ascending order of size from top to bottom (i.e., each disk sits on top of an even larger one). You have the following constraints:
(1) Only one disk can be moved at a time.
(2) A disk is slid off the top of one tower onto the next tower.
(3) A disk can only be placed on top of a larger disk.
Write a program to move the disks from the first tower to the last using stacks.
解答
//3.4
//In the classic problem of the Towers of Hanoi, you have 3 rods and N disks of different sizes which can slide onto any tower.The puzzle starts with disks sorted in ascending order of size from top to bottom(e.g., each disk sits on top of an even larger one).You have the following constraints :
//
//Only one disk can be moved at a time.
//A disk is slid off the top of one rod onto the next rod.
//A disk can only be placed on top of a larger disk.
//Write a program to move the disks from the first rod to the last using Stacks
#include <iostream>
#include <stack>
#include <windows.h>
using namespace std;
//递归方法
//将n个碟子从src经过buf搬到dst
void moveDisks(int n, char src, char buf, char dst, int &step)
{
if (n == 1)
{
cout << step++ << ":\t" << 0 << " 从 " << src << " 到 " << dst << endl;
return;
}
moveDisks(n - 1, src, dst, buf, step);
cout << step++ << ":\t" << n - 1 << " 从 " << src << " 到 " << dst << endl;
moveDisks(n - 1, buf, src, dst, step);
}
struct op
{
int begin, end;
char src, buf, dst;
op(){}
op(int pbegin, int pend, int psrc, int pbuf, int pdst) :begin(pbegin), end(pend), src(psrc), buf(pbuf), dst(pdst){}
};
//迭代方法
void hanoi(int n, char src, char buf, char dst)
{
stack<op> st;
op tmp;
st.push(op(0, n - 1, src, buf, dst));
int step = 0;
while (!st.empty())
{
tmp = st.top();
st.pop();
if (tmp.begin != tmp.end)
{
st.push(op(tmp.begin, tmp.end - 1, tmp.buf, tmp.src, tmp.dst));
st.push(op(tmp.end, tmp.end, tmp.src, tmp.buf, tmp.dst));
st.push(op(tmp.begin, tmp.end - 1, tmp.src, tmp.dst, tmp.buf));
}
else
{
cout << step++ << ":\t" << "Move disk " << tmp.begin << " from " << tmp.src << " to " << tmp.dst << endl;
}
}
cout << "total: " << step << " = 2 ^ " << n << " - 1" << " steps" << endl;
}
int main()
{
cout << "汉 诺 塔 游 戏" << endl;
int n = 5;
int step = 0;
cout << "总碟数: " << n << endl;
cout << "步骤:" << endl;
moveDisks(n, 'A', 'B', 'C', step);
cout << "共 " << step << " = 2 ^ " << n << " - 1" << " 步" << endl;
cout << endl;
hanoi(n, 'A', 'B', 'C');
system("pause");
}