您的位置:首页 > 其它

hano塔非递归

2013-10-21 16:11 344 查看
#include <stdio.h>
const int MaxSize=100;
struct
{
int vn;
char x,y,z;
int flag;
}st[MaxSize];
int top=-1;
void hano2(int n,char X,char Y,char Z)
{
top++;
st[top].vn=n;
st[top].x=X;
st[top].y=Y;
st[top].z=Z;
st[top].flag=1;
while (top>-1)
{
int vn1;
char x1,y1,z1;
if (st[top].flag==1)
{
vn1=st[top].vn;
x1=st[top].x;
y1=st[top].y;
z1=st[top].z;
if (st[top].vn==2)
{
top--;
top++;
st[top].vn=vn1-1;
st[top].x=x1;
st[top].y=z1;
st[top].z=y1;
st[top].flag=0;
top++;
st[top].vn=1;
st[top].x=x1;
st[top].y=z1;
st[top].z=y1;
st[top].flag=0;
top++;
st[top].vn=vn1-1;
st[top].x=y1;
st[top].y=x1;
st[top].z=z1;
st[top].flag=0;
}
else
{
top--;
top++;
st[top].vn=vn1-1;
st[top].x=x1;
st[top].y=z1;
st[top].z=y1;
st[top].flag=1;
top++;
st[top].vn=1;
st[top].x=x1;
st[top].y=z1;
st[top].z=y1;
st[top].flag=0;
top++;
st[top].vn=vn1-1;
st[top].x=y1;
st[top].y=x1;
st[top].z=z1;
st[top].flag=1;
}
}
else if (st[top].flag==0)
{
printf("move %c to %c\n",st[top].x,st[top].z);
top--;
}
}
}
void main()
{
char X='X';
char Y='Y';
char Z='Z';
hano2(5,X,Y,Z);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: