汉诺塔算法

来源:互联网 发布:收据软件 编辑:程序博客网 时间:2024/06/03 15:47
/**               Hanoi思路:用递归//栈*假设开始柱子:A,中间柱子:B,目标柱子:C*第一步:将n-1个盘子从A借助C移到B*第二步:将第n个盘子从A到C*第三步:将n-1个盘子从B借助A移到C**///递归算法:#include <iostream>#include<stdio.h>using namespace std;void Hanoi(int plate, char A,char B,char C);static int count;//计算移动的总次数int main(){    int plate;    while(cin>>plate)    {        getchar();        char start;        char depend;        char destination;        scanf("%c%*c%c%*c%c%*c",&start,&depend,&destination);//输入起始柱,中间柱和目标柱        count=0;        Hanoi(plate,start,depend,destination);        cout<<endl;    }    return 0;}void Hanoi(int plate, char A,char B,char C){    if(plate==1)       {        cout<<"第"<<++count<<"次:";        cout<<"第"<<plate<<"个盘子从"<<A<<"移到"<<C<<endl;       }    else    {        Hanoi(plate-1,A,C,B);//将n-1个从 A借助 C 移到 B        cout<<"第"<<++count<<"次:";        cout<<"第"<<plate<<"个盘子从"<<A<<"移到"<<C<<endl;//将最底下的最大盘子从A移到C        Hanoi(plate-1,B,A,C);//将B上的n-1个盘子由B借助A移到C    }}//栈#include<iostream>#include<stack>#include<stdio.h>using namespace std;struct EveryTime//每次移动{    int CurPlateNum;    char start;    char dependent;    char destination;    EveryTime(){}    EveryTime(int n, char A, char B, char C):CurPlateNum(n),start(A),dependent(B),destination(C){}};int main(){    stack<EveryTime> stk;    EveryTime cur;    int n;    int count;//统计需要移动的次数    while(cin>>n)    {        getchar();        char start;        char depend;        char destination;        scanf("%c%*c%c%*c%c%*c",&start,&depend,&destination);//输入起始柱,中间柱和目标柱        count=0;        stk.push(EveryTime(n,start,depend,destination));        while(!stk.empty())        {            cur=stk.top();//用cur保存栈顶,下面用cur进行讨论            stk.pop();//弹出栈顶            if(cur.CurPlateNum==1)            {                cout<<"第"<<++count<<"次:";                cout<<"第"<<cur.CurPlateNum<<"个盘子从"<<cur.start<<"移到"<<cur.destination<<endl;            }            else//根据栈先进后出特点应该将顺序倒过来.因为递归可以独立进行,而栈先进去的元素等会晚执行            {                stk.push(EveryTime(cur.CurPlateNum-1,cur.dependent,cur.start,cur.destination));//将n-1个从B(dependent)借助A(start)移到C(destination)                stk.push(EveryTime(1,cur.start,cur.dependent,cur.destination));//将第n个由A(start)移到C(destination)               stk.push(EveryTime(cur.CurPlateNum-1,cur.start,cur.destination,cur.dependent));//将n-1个从A(start)借助C(destination)移到B(depenent)            }        }    }    return 0;}

原创粉丝点击