1. 程式人生 > >[CareerCup] 3.4 Towers of Hanoi 漢諾塔

[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.

經典的漢諾塔問題,記得當年文曲星流行的日子,什麼漢諾塔啊,英雄壇說啊,華容道啊,都是文曲星上的經典遊戲,當時還覺得漢諾塔蠻難玩的,大學裡學資料結構的時候才發現原來用遞迴這麼容易解決。那麼我們來看看用遞迴如何實現:

假如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 > 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; }