[CareerCup] 3.4 Towers of Hanoi 汉诺塔

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.

经典的汉诺塔问题,记得当年文曲星流行的日子,什么汉诺塔啊,英雄坛说啊,华容道啊,都是文曲星上的经典游戏,当时还觉得汉诺塔蛮难玩的,大学里学数据结构的时候才发现原来用递归这么容易解决。那么我们来看看用递归如何实现:

aaarticlea/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAMCAgMCAgMDAwMEAwMEBQgFBQQEBQoHBwYIDAoMDAsKCwsNDhIQDQ4RDgsLEBYQERMUFRUVDA8XGBYUGBIUFRT/2wBDAQMEBAUEBQkFBQkUDQsNFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBT/wAARCADHAh0DAREAAhEBAxEB/8QAHQABAQEAAgMBAQAAAAAAAAAAAAcGAQIDBAUICf/EAFAQAQAABAIFBAsNBAcJAQAAAAABAgMGBAUHEReU0xIhNlcIFTEyQXN2tMLR0hMUGCJRVFZhdHWRk7I3VXGhIzM1Q2JygRYmNDhCR1Kxs1P/xAAUAQEAAAAAAAAAAAAAAAAAAAAA/8QAFBEBAAAAAAAAAAAAAAAAAAAAAP/aAAwDAQACEQMRAD8A/qmAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA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

假如n = 1,直接将Disk 1移到Tower C即可

假如n = 2,需要三步:
1. 把Disk 1 从Tower A 移到 Tower B
2. 把Disk 2 从Tower A 移到 Tower C
3. 把Disk 1 从Tower B 移到 Tower C

假如n = 3,需要如下几步:
1. 我们首先把上面两层移到另一个位置,我们在n = 2时实现了,我们将其移到 Tower B
2. 把Disk 3 移到Tower C
3. 然后把上面两层移到Disk 3,方法跟n = 2时相同

假如n = 4,需要如下几步:
1. 把Disk 1, 2, 3 移到 Tower B,方法跟n = 3时相同
2. 把Disk 4 移到 Tower C
3. 把Disk 1, 2, 3 移到 Tower C

这时典型的递归方法,实现方法参见下面代码:

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 > ) {
moveDisks(n - , buffer, destination);
moveTopTo(destination);
buffer.moveDisks(n - , destination, *this);
}
} private:
stack<int> _disks;
int _idx;
}; int main() {
int n = ;
vector<Tower> towers;
for (int i = ; i < ; ++i) {
Tower t(i);
towers.push_back(t);
}
for (int i = n - ; i >= ; --i) {
towers[].add(i);
}
towers[].moveDisks(n, towers[], towers[]);
return ;
}
上一篇:The Towers of Hanoi Revisited---(多柱汉诺塔)


下一篇:vs2019新建数据库后插入中文变问号