专注收集记录技术开发学习笔记、技术难点、解决方案
网站信息搜索 >> 请输入关键词:
您当前的位置: 首页 > C语言

关于用栈实现迷宫求解解决办法

发布时间:2011-06-28 16:17:23 文章来源:www.iduyao.cn 采编人员:星星草
关于用栈实现迷宫求解
#include<stdio.h>
#include<stdlib.h>

struct step
{
int a;
int b;
};
struct step* push(step *top,int i,int j)
{
top=top+sizeof(step);
top->a=i;
top->b=j;
return top;
}
void print(step *top,step *base)
{
while(top!=base)
{
top=top-sizeof(step);
printf("(%d,%d)\n",top->a,top->b);
}
}
int compare(step *top,step *base,int i,int j)
{
int x;
if(top==base)
{
x=1;
}
while(top!=base)
{
if(top->a==i&&top->b==j)
{
x=1;
break;
}
else
{
x=0;
}
top=top-sizeof(step);
}
return x;
}
main()
{
int a[10][10];
int i,j;
step *top,*base;
for(i=0;j<10;i++)
{
for(j=0;j<10;j++)
{
a[i][j]=1;
}
}
for(i=0;i<10;i++)
{
a[0][i]=0;
a[i][0]=0;
a[9][i]=0;
a[i][9]=0;
}
a[1][3]=a[1][7]=a[2][3]=a[2][7]=a[3][5]=a[3][6]=a[4][2]=a[4][3]=a[4][4]=a[5][4]=a[6][2]=a[6][6]=a[7][2]=a[7][3]=a[7][4]=a[7][6]=a[7][7]=a[8][1]=0;
base=(step*)malloc(1024*sizeof(step));
top=base;
top->a=1;
top->b=1;
while(top->a!=9&&top->b!=9)
{
i=top->a;
j=top->b;
if(a[i][j+1]==1&&compare(top,base,i,j+1)!=0)
{
top=push(top,i,j+1);
}
else if(a[i+1][j]==1&&compare(top,base,i+1,j)!=0)
{
top=push(top,i+1,j);
}
else
{
a[i][j]=0;
top=top-sizeof(step);
}
}
print(top,base);
}


运行没有报错 但没有结果,调试时发现 a[i][j] a[i][j+1] a[i+1][j]都是没有值的 但之前明明已经赋值好了 
编码有点长 麻烦大家指教一下了 谢谢!

------解决方案--------------------
C/C++ code
#include<stdio.h>
#include<stdlib.h>

struct step
{
int a;
int b;
};
struct step* push(step *top,int i,int j)
{
top=top+sizeof(step);//把这里改为top++;
top->a=i;
top->b=j;
return top;
}
void print(step *top,step *base)
{
while(top!=base)
{
top=top-sizeof(step);//改为top--;
printf("(%d,%d)\n",top->a,top->b);
}
}
int compare(step *top,step *base,int i,int j)
{
int x;
if(top==base)
{
x=1;
}
while(top!=base)
{
if(top->a==i&&top->b==j)
{
x=1;
break;
}
else
{
x=0;
}
top=top-sizeof(step);//这里,
}
return x;
}
main()
{
int a[10][10];
int i,j;
step *top,*base;
for(i=0;j<10;i++)
{
for(j=0;j<10;j++)
{
a[i][j]=1;
}
}
for(i=0;i<10;i++)
{
a[0][i]=0;
a[i][0]=0;
a[9][i]=0;
a[i][9]=0;
}
a[1][3]=a[1][7]=a[2][3]=a[2][7]=a[3][5]=a[3][6]=a[4][2]=a[4][3]=a[4][4]=a[5][4]=a[6][2]=a[6][6]=a[7][2]=a[7][3]=a[7][4]=a[7][6]=a[7][7]=a[8][1]=0;
base=(step*)malloc(1024*sizeof(step));
top=base;
top->a=1;
top->b=1;
while(top->a!=9&&top->b!=9)
{
i=top->a;
j=top->b;
if(a[i][j+1]==1&&compare(top,base,i,j+1)!=0)
{
top=push(top,i,j+1);
}
else if(a[i+1][j]==1&&compare(top,base,i+1,j)!=0)
{
top=push(top,i+1,j);
}
else
{
a[i][j]=0;
top=top-sizeof(step);//这里。。
}
}
print(top,base);
}
友情提示:
信息收集于互联网,如果您发现错误或造成侵权,请及时通知本站更正或删除,具体联系方式见页面底部联系我们,谢谢。

其他相似内容:

热门推荐: