📄 5_46.cpp
字号:
#include<iostream.h>
#define maxlen 50
void hanoi(int n,char a,char b,char c)
{
struct stack
{
int no,ns;
char x,y,z;
}st[maxlen];
int top=1,n1,a1,b1,c1;
st[top].no=1; //初值入栈
st[top].ns=n;
st[top].x=a;
st[top].y=b;
st[top].z=c;
while(top>0)
{
if(st[top].no==1)
{
n1=st[top].ns; //退栈hanoi(n,x,y,z)
a1=st[top].x;
b1=st[top].y;
c1=st[top].z;
top--;
top++; //将hanoi(n-1,x,z,y)入栈
st[top].no=1;
st[top].ns=n1-1;
st[top].x=b1;
st[top].y=a1;
st[top].z=c1;
top++; //将第n个圆盘从x移到z
st[top].no=0;
st[top].ns=n1;
st[top].x=a1;
st[top].y=c1;
top++; //hanoi(n-1,y,x,z)入栈
st[top].no=1;
st[top].ns=n1-1;
st[top].x=a1;
st[top].y=c1;
st[top].z=b1;
}
while(top>0 && (st[top].no==0 || st[top].ns==1))
{
if(top>0 && st[top].no==0)
{
cout<<"\t将第"<<st[top].ns<<"个盘片从"
<<st[top].x<<"移动到"<<st[top].y<<endl;
top--;
}
if(top>0 && st[top].ns==1) //将第n个圆盘从x移到z并退栈
{
cout<<"\t将第"<<st[top].ns<<"个盘片从"
<<st[top].x<<"移动到"<<st[top].z<<endl;
top--;
}
}
}
}
void main()
{
int n=3;
cout<<"hanoi(3)非递归求解结果:"<<endl;
hanoi(n,'x','y','z');
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -