zoukankan      html  css  js  c++  java
  • 227 用栈模拟汉诺塔问题

    原题网址:https://www.lintcode.com/problem/mock-hanoi-tower-by-stacks/description

    描述

    在经典的汉诺塔问题中,有 3 个塔和 N 个可用来堆砌成塔的不同大小的盘子。要求盘子必须按照从小到大的顺序从上往下堆 (如,任意一个盘子,其必须堆在比它大的盘子上面)。同时,你必须满足以下限制条件:

    (1) 每次只能移动一个盘子。
    (2) 每个盘子从堆的顶部被移动后,只能置放于下一个堆中。
    (3) 每个盘子只能放在比它大的盘子上面。

    请写一段程序,实现将第一个堆的盘子移动到最后一个堆中。

    标签
     
    思路:汉诺塔——经典递归问题。解法可参考:用栈模拟汉诺塔问题-LintCode
     
    简单说来就是如果只有一个盘子需要移动,直接放到目标塔上;如果有n(n>1)个盘子需要移动:
    1 先把n-1个盘子移动到缓冲塔上,此时目标塔做缓冲辅助
    2 再把最下面的盘子移动到目标塔
    3 最后再把这n-1个盘子移动到目标塔,注意此时缓冲塔是最开始的塔(哪个塔为空就用哪个塔做缓冲)
     
    PS:想不通构造函数的参数有啥用……盘子数?好像不是
     
    AC代码:
    class Tower {
    private:
        stack<int> disks;
    public:
        /*
        * @param i: An integer from 0 to 2
        */
        Tower(int i) {
            // create three towers
        }
    
        /*
         * @param d: An integer
         * @return: nothing
         */
        void add(int d) {
            // Add a disk into this tower
            if (!disks.empty() && disks.top() <= d) {
                printf("Error placing disk %d", d);
            } else {
                disks.push(d);
            }
        }
    
        /*
         * @param t: a tower
         * @return: nothing
         */
        void moveTopTo(Tower &t) {
            // Move the top disk of this tower to the top of t.
            int tmp=disks.top();
            disks.pop();
            t.add(tmp);
        }
    
        /*
         * @param n: An integer
         * @param destination: a tower
         * @param buffer: a tower
         * @return: nothing
         */
        void moveDisks(int n, Tower &destination, Tower &buffer) {
            // Move n Disks from this tower to destination by buffer tower
            if (n<=0)
            {
                return ;
            }    
            if (n==1)
            {
                moveTopTo(destination);
                return ;
            }
            moveDisks(n-1,buffer,destination);
            moveTopTo(destination);
            buffer.moveDisks(n-1,destination,*this);//注意1 最后一个参数是*this,不是buffer,缓冲塔初始盘子数应为空;2 是buffer调用moveDisks,将buffer中的盘子转移;
        }
    
        /*
         * @return: Disks
         */
        stack<int> getDisks() {
            // write your code here
            return disks;
        }
    };
    
    /**
     * Your Tower object will be instantiated and called as such:
     * vector<Tower> towers;
     * for (int i = 0; i < 3; i++) towers.push_back(Tower(i));
     * for (int i = n - 1; i >= 0; i--) towers[0].add(i);
     * towers[0].moveDisks(n, towers[2], towers[1]);
     * print towers[0], towers[1], towers[2]
    */

    其它参考:

  • 相关阅读:
    Kerberos-KDC
    samba后台进程及安全模式简介
    samba服务器详细配置(非域模式)
    windows常用net use命令
    samba常用命令
    ORA-24324、ORA-12560、ORA-12514
    oracle的启动和关闭
    Oracle 监听配置详解(转载)
    linux加入windows域之完美方案(转载)
    怎样识吉他谱
  • 原文地址:https://www.cnblogs.com/Tang-tangt/p/9193988.html
Copyright © 2011-2022 走看看