首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

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

2012-02-10 
关于用栈实现迷宫求解#includestdio.h#includestdlib.hstruct step{int aint b}struct step* push(

关于用栈实现迷宫求解
#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);} 

热点排行
Bad Request.