• [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;
    }
  • 相关阅读:
    centos8重置root密码
    Mysql查询某列最长字符串记录
    ssm连接mysql出现Connections could not be acquired from the underlying database 问题
    spring-基于xml配置Bean
    WinForm控件命名缩写
    SQL Server 将一张表的某个字段更新到另一张表中
    SQL Server 取出指定字符后字符串(用于分割)
    小白学CMD下运行MySQL
    Bootstrap3.0和bootstrap2.x的区别
    有关js弹出提示框几种方法
  • 原文地址:https://www.cnblogs.com/grandyang/p/4677404.html
Copyright © 2020-2023  润新知