[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;
}

 本文转自博客园Grandyang的博客,原文链接:汉诺塔[CareerCup] 3.4 Towers of Hanoi ,如需转载请自行联系原博主。

相关文章
|
5月前
|
算法
|
5月前
|
Java
hdu-2544-最短路(SPFA)
hdu-2544-最短路(SPFA)
31 0
|
5月前
|
机器学习/深度学习
N皇后问题(HDU—2253)
N皇后问题(HDU—2253)
汉诺塔问题
汉诺塔(Tower of Hanoi),又称河内塔,是一个源于印度古老传说的益智玩具。大梵天创造世界的时候做了三根柱子,在一根柱子上从下往上按照大小顺序摞着64片黄金圆盘。大梵天命令婆罗门把圆盘从下面开始按大小顺序重新摆放在另一根柱子上。并且规定,在小圆盘上不能放大圆盘,在三根柱子之间一次只能移动一个圆盘。
67 0
|
12月前
汉诺塔(hanoi)问题从0到1详解
汉诺塔(hanoi)问题从0到1详解
104 0
|
Java C语言
【JavaOJ】汉诺塔问题
JavaOJ & 汉诺塔问题
76 0
|
C++
【C/C++】汉诺塔问题
## 汉诺塔问题相传来源于印度教的天神汉诺。据说汉诺在创造地球时建了一座神庙,神庙里面有三根柱子,汉诺将64个直径大小不同的盘子按照从大到小的顺序依次放置在第一个柱子上,形成金塔(即汉诺塔)。天神汉诺每天让庙里的僧侣们将第一根柱子上的64个盘子借助第二根柱子全部移动大第三根柱子上,并说:“当这64个盘子全部移动到第三根柱子上时,世界末日也就要到了!”这就是著名的汉诺塔问题。
130 0
【C/C++】汉诺塔问题