1. 程式人生 > >新部落格地址http://www.cnblogs.com/millionsmultiplication/

新部落格地址http://www.cnblogs.com/millionsmultiplication/

演算法篇-用棧來求解漢諾塔問題

閱讀了java版的《程式設計師程式碼面試指南 IT名企演算法與資料結構題目最優解》後,用c++以自己的想法完成了這道題

完整題目

在漢諾塔規則的基礎上,限制不能從最左的塔移動到最右的塔上,必須經過中間的塔,移動的跨度只能是一個塔。當塔有N層的時候,列印最優移動過程和最優移動步數。
看到原題我實際上並不能理解這道題,百度後才理解
相傳在古印度聖廟中,有一種被稱為漢諾塔(Hanoi)的遊戲。該遊戲是在一塊銅板裝置上,有三根杆(編號A、B、C),在A杆自下而上、由大到小按順序放置64個金盤(如下圖)。遊戲的目標:把A杆上的金盤全部移到C杆上,並仍保持原有順序疊好。操作規則:每次只能移動一個盤子,並且在移動過程中三根杆上都始終保持大盤在下,小盤在上,操作過程中盤子可以置於A、B、C任一杆上。

題目限制:

1.一次只能移動一個數字
2.大的數字不能出現在小的盤子(數字)的上方(棧頂)
3.左右兩棧盤子(數字)移動必須經過中間的塔

遞迴實現
遞迴實現基本依照書本實現思路

int minstep;//步數
//遞迴

void move(int num, string from, string to)
{
    if (num == 1)
    {
        if (from=="mid" || to == "mid")
        {
            cout << "Move " << num << " from "
<< from << " to " << to << endl; minstep+=1; } else { cout << "Move " << num << " from " << from << " to " << "mid" << endl; cout << "Move " << num << " from " << "mid"
<< " to " << to << endl; minstep += 2; } } else { if (from=="mid" || to == "mid") { string another = (from._Equal("left") || to._Equal("left")) ? "right" : "left"; move(num - 1, from, another); cout << "Move " << num << " from " << from << " to " << to << endl; minstep += 1; move(num - 1, another, to); } else { move(num-1, from, to); cout << "Move " << num << " from " << from << " to " << "mid" << endl; minstep += 1; move(num - 1, to, from); cout << "Move " << num << " from " << "mid" << " to " << to << endl; minstep += 1; move(num - 1, from, to); } } } void HanoiProblemnBydfd(int num) { if (num <= 0) return; minstep = 0; move(num, "left", "right"); }

測試

int main()
{
    HanoiProblemnBydfd(3);
    cout << minstep << endl;

    return 0;
}

棧模擬
棧模擬實現和書本略有不同,由於每次移動只能出現一種方式,所以把所有盤子的移動判斷完全由程式判斷

#include <stack>
#include <iostream>
#include <string>
using namespace std;
long minstep = 0;//最小步數
//非遞迴,用棧模擬
class HanoiStack {
private:
    stack<int> LeftP;
    stack<int> MidP;
    stack<int> RightP;
    int n;
    string lastfrom;
    string lastto;
    void Move(string from,string to)
    {
        if (from== lastto&&to== lastfrom) return;

        int fromVal=0;
        if (from == "left"&&!LeftP.empty())
        {
            fromVal = LeftP.top();
            //LeftP.pop();
        }
        else if (from == "mid" && !MidP.empty())
        {
            fromVal = MidP.top();
            //MidP.pop();
        }
        else if (from == "right" && !RightP.empty())
        {
            fromVal = RightP.top();
            //RightP.pop();
        }
        if (fromVal == 0) return;
        if (to == "left")
        {
            if(LeftP.empty()) LeftP.push(fromVal);
            else if(fromVal<LeftP.top()) LeftP.push(fromVal);
            else return;
        }
        else if(to=="mid") 
        {
            if (MidP.empty()) MidP.push(fromVal);
            else if (fromVal<MidP.top()) MidP.push(fromVal);
            else return;
        }
        else if (to == "right")
        {
            if (RightP.empty()) RightP.push(fromVal);
            else if (fromVal<RightP.top()) RightP.push(fromVal); 
            else return;
        }
        Pop(from);
        lastto = to;
        lastfrom = from;
        cout << "Move " << fromVal << " from " << from << " to " << to << endl;
        minstep += 1;
    }
    void Pop(string from)
    {
        if (from == "left" && !LeftP.empty())
        {

            LeftP.pop();
        }
        else if (from == "mid" && !MidP.empty())
        {

            MidP.pop();
        }
        else if (from == "right" && !RightP.empty())
        {

            RightP.pop();
        }
    }
public:
    HanoiStack(int n)
    {
        for (int i = n; i >0; i--)
        {
            LeftP.push(i);
        }
        this->n = n;
        minstep = 0;
    }
    void HanoiProblem()
    {
        while (RightP.size() != n)
        {
            Move("left", "mid");
            Move("mid", "left");
            Move("mid", "right");           
            Move("right", "mid");               
        }
        cout << minstep << endl;
    }

};

測試

int main()
{
    /*HanoiProblemnBydfd(3);
    cout << minstep << endl;*/
    HanoiStack  test = HanoiStack(3);
    test.HanoiProblem();
    return 0;
}

相關推薦

部落地址http://www.cnblogs.com/millionsmultiplication/

演算法篇-用棧來求解漢諾塔問題 閱讀了java版的《程式設計師程式碼面試指南 IT名企演算法與資料結構題目最優解》後,用c++以自己的想法完成了這道題 完整題目 在漢諾塔規則的基礎上,限制不能從最左的塔移動到最右的塔上,必須經過中間的塔,移動的跨度

部落遷移http://www.cnblogs.com/xzz_233/

比賽連結 傻逼題,列舉即可。 #include<cstdio> #include<cstdlib> #include<algorithm> bool k[10

部落地址www.yizhen-blog.com 歡迎交流

在學習深度學習相關知識,無疑都是從神經網路開始入手,在神經網路對引數的學習演算法bp演算法,接觸了很多次,每一次查詢資料學習,都有著似懂非懂的感覺,這次趁著思路比較清楚,也為了能夠讓一些像我一樣疲於各

部落地址:blog.songchunmin.com

0. Core Image 作為設計和體驗方面的領導者,蘋果自己對圖片效果和圖片處理的支援一定是非常好的,在iOS平臺上,5.0之後就出現了Core Image的API。Core Image的API被放在CoreImage.framework庫中。 在iOS和OS

部落已搬遷到http://www.cnblogs.com/cniwoq/

簡單計算器 Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others) Total Submission(s): 18056    Accepted Submiss

部落已轉移至:http://www.cnblogs.com/wu-jian/

//GridView中有所不同protectedvoid gv_RowDataBound(object sender, GridViewRowEventArgs e)    {        if (e.Row.RowType == DataControlRowType.DataRow)        {  

python學習——day9(ssh,線程和進程,信號量,隊列,生產者消費者模型) Alex地址http://www.cnblogs.com/alex3714/articles/5230609.html

png 接口 count() day bound 共享 car 共享內存 top 一、python上模擬ssh 1.ssh,ssh_ftp pass 2.ssh 密鑰 pass 二、線程,進程 定義: 進程: 是對各種資源管理的集合,qq 要以一個整體的形式暴露給操

Mysql查詢優化之 觸發器加中間表 方法優化count()統計大資料量總數問題 轉載請註明原文地址http://www.cnblogs.com/ygj0930/p/6138288.ht

    在上一篇博文我們提到,分頁有三種方法。其中,第三種是我們最常用的。然而,在實際應用過程中我們會發現,select count(*) from tname 語句在統計某表內記錄總數時,如果表內資料量達到一定規模(比如100W條),這個語句就會執行得非常慢。有什麼辦法可以加快統計出表內記錄總數呢?  

使用ajax提交form表單,包括ajax文件上傳 轉http://www.cnblogs.com/zhuxiaojie/p/4783939.html

ima option img jquery選擇器 open request resp logs ges 使用ajax提交form表單,包括ajax文件上傳 前言 使用ajax請求數據,很多人都會,比如說: $.post(path,{data:data},function

第一個 vuejs http://www.cnblogs.com/avon/p/5943008.html

match 配置 cnblogs wid 訪問路徑 keep trap 頁面切換 ssa vue路由的使用 ue-router是Vue.js官方的路由插件,它和vue.js是深度集成的,適合用於構建單頁面應用。vue的單頁面應用是基於路由和組件的,路由用於設定訪問路

http://www.cnblogs.com/chenguangpeng/p/6188352.html 遞歸下降

sca turn htm www har ring 次數 http %d #include<stdio.h> #include<string> char str[50]; int index=0; void E(); /

nodeJS中的包 npm install http://www.cnblogs.com/xiaohuochai/archive/2017/05/20/6882027.html

.html 方法 href 對象 inux gif 例子 配置文件 安裝 前面的話   Node組織了自身的核心模塊,也使得第三方文件模塊可以有序地編寫和使用。但是在第三方模塊中,模塊與模塊之間仍然是散列在各地的,相互之間不能直接引用。而在模塊之外,包和NPM則是將模塊

本人最新博客地址:http://www.linuxmysql.com:88

博客本人最新博客地址:www.linuxmysql.com:88本文出自 “阮勝昌的技術博客” 博客,請務必保留此出處http://rscpass.blog.51cto.com/771159/1927960本人最新博客地址:http://www.linuxmysql.com:88

轉載智能家居 作者:熱情的沙漠 出處:http://www.cnblogs.com/buptzym/

它的 必須 環境光 暴力破解 研究生 破解 開始 印象 提醒 理工男打造帝都89平智能家庭 畢業後的2016年年初,搬入新家,總算不用在出租屋裏鬼混了,於是就想把之前童年的夢想:智能家居+家庭影院好好實現一下~ 相比帝都高昂的房價,這些東東還湊合玩得起,不過在有限預

<轉載> MySQL 架構 http://www.cnblogs.com/winner-0715/p/6863802.html

ast 基礎 我們 以及 基於 storage 投影 itl uid 1.MySQL整體邏輯架構 我們先下圖看看MySQL整體邏輯架構(MySQL’s Logical Architecture) 圖1

轉載 logback的使用和logback.xml詳解 http://www.cnblogs.com/warking/p/5710303.html

version tor red java代碼 根節點 ext private 字符串 npe logback的使用和logback.xml詳解 一、logback的介紹  Logback是由log4j創始人設計的另一個開源日誌組件,官方網站: http://logb

liftover[裝載自http://www.cnblogs.com/emanlee/p/5064630.html]

admin nom provides target mod man repr head html Lift genome positions Genome positions are best represented in BED format. UCSC provides

Java String和Date的轉換 轉http://www.cnblogs.com/bmbm/archive/2011/12/06/2342264.html

ref integer public cat 標記 星期 import 轉換 star Java String和Date的轉換 String—>Date方法一: String dateString = "2012-12-06 "; try {

數字證書原理 - 轉自 http://www.cnblogs.com/JeffreySun/archive/2010/06/24/1627247.html

在操作 computer ide iis 中斷 計算 虛擬 from 上進 文中首先解釋了加密解密的一些基礎知識和概念,然後通過一個加密通信過程的例子說明了加密算法的作用,以及數字證書的出現所起的作用。接著對數字證書做一個詳細的解釋,並討論一下windows中數字證書的管理

數據挖掘 - 算法 - ID3 - 轉自 http://www.cnblogs.com/dztgc/archive/2013/04/22/3036529.html

str htm bar c++代碼 度量 進行 初始化 ++ 預測 1 簡介   決策樹學習是一種逼近離散值目標函數的方法,在這種學習到的函數被表示為一棵決策樹。 2 決策樹表示   決策樹通過把實例從根節點排列到某個葉子結點來分類實例,葉子結點即為實例所屬的分類。樹上的