现在的位置: 首页 > 综合 > 正文

c++解决汉诺塔,显示每一步的碟子情况 C++ hanoi with trace of every step

2013年05月02日 ⁄ 综合 ⁄ 共 1481字 ⁄ 字号 评论关闭

 

 

#include "stdafx.h"

#include <iostream>

#include <stack>

 

void StartHanoi(int n);

void Hanoi(int length, std::stack<int>* source, std::stack<int>* middle, std::stack<int>* destination);

void PrintStack();

void PrintAStack(std::stack<int> stackToBePrint);

 

std::stack <int> source, middle, destination;

 

int _tmain(int argc, _TCHAR* argv[])

{

    int iNumDisc = 0;

    while(iNumDisc<=0)

    {

       std::cin>>iNumDisc;

    }

    StartHanoi(iNumDisc);

    return 0;

}

 

void StartHanoi(int n)

{  

    if(n<=0)

    {

       return;

    }

    for(int i=n;i>0;i--)

    {

       source.push(i);

    }

    PrintStack();

    Hanoi(source.size(),&source,&middle,&destination);

}

 

void Hanoi(int length, std::stack<int>* psource, std::stack<int>* pmiddle, std::stack<int>* pdestination)

{

    if(length==0)

    {

       return;

    }

    //  Move n-1 to middle

    if(length>1)

    {

       Hanoi(length-1, psource, pdestination, pmiddle);

    }

    // Move last disc in the source pole to destination pole

    int temp = psource->top();

    psource->pop();

    pdestination->push(temp);

    PrintStack();

    //  Move middle to destination

    if(length>1)

    {

       Hanoi(length-1, pmiddle, psource, pdestination);

    }

}

 

void PrintStack()

{

    PrintAStack(source);

    PrintAStack(middle);

    PrintAStack(destination);

    std::cout<<std::endl;

}

 

void PrintAStack(std::stack<int> stackToBePrint)

{

    if(stackToBePrint.size()<=0)

    {

       std::cout<<'-'<<std::endl;

       return;

    }

    //  source

    while(stackToBePrint.size()>0)

    {

       int temp = stackToBePrint.top();

       stackToBePrint.pop();

       std::cout<<temp<<' ';

    }

    std::cout<<std::endl;

}

抱歉!评论已关闭.