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.
经典的汉诺塔问题,记得当年文曲星流行的日子,什么汉诺塔啊,英雄坛说啊,华容道啊,都是文曲星上的经典游戏,当时还觉得汉诺塔蛮难玩的,大学里学数据结构的时候才发现原来用递归这么容易解决。那么我们来看看用递归如何实现:
假如n = 1,
class Tower { public: Tower(int i) : _idx(i) {} int index() { return _idx; } void add(int d) { if (!_disks.empty() && _disks.top() <= d) { cout << "Error placing disk " << d << endl; } else { _disks.push(d); } } void moveTopTo(Tower &t) { int top = _disks.top(); _disks.pop(); t.add(top); cout << "Move disk " << top << " from " << index() << " to " << t.index() << endl; } void moveDisks(int n, Tower &destination, Tower &buffer) { if (n > 0) { moveDisks(n - 1, buffer, destination); moveTopTo(destination); buffer.moveDisks(n - 1, destination, *this); } } private: stack<int> _disks; int _idx; }; int main() { int n = 10; vector<Tower> towers; for (int i = 0; i < 3; ++i) { Tower t(i); towers.push_back(t); } for (int i = n - 1; i >= 0; --i) { towers[0].add(i); } towers[0].moveDisks(n, towers[2], towers[1]); return 0; }
时间: 2024-11-03 22:52:35