问题遇到的现象和发生背景
上机课敲了两个小时,求指点!
问题相关代码,请勿粘贴截图
#include<stdio.h>
#include<malloc.h>
#define m 4
#define n 4
#define max 100
int mg[m+2][n+2]=
{
{1,1,1,1,1,1},
{1,0,0,0,1,1},
{1,0,1,0,0,1},
{1,0,0,0,1,1},
{1,1,0,0,0,1},
{1,1,1,1,1,1}
};
typedef struct
{
int i,j;//行,列
int di ;
} box;
typedef struct
{
box data[max];
int top;
} st;
void initst(st *& s)//初始化
{
s=(st*)malloc(sizeof(st));
s->top=-1;
}
bool push(st *&s,box e)//进栈
{
if(s->top==max-1)
return false;
s->top++;
s->data[s->top]=e;
return true;
}
bool stempty(st *s)//检查空栈
{
if(s->top==-1)
return false;
return true;
}
bool gettop(st *s,box &e)//取栈顶
{
if(s->top==-1)
return false;
e=s->data[s->top];
return true;
}
bool pop(st *&s,box &e)//出栈
{
if(s->top==-1)
return false;
e=s->data[s->top];
s->top--;
return true;
}
void destroyst(st *&s)//销毁栈
{
free(s);
}
bool mgpath(int xi,int yi,int xe,int ye)
{
box path[max],e;
int i,j,di,il,jl,k;
bool find;
st *s;
initst(s);
e.i=xi;e.j=yi;e.di=-1;
mg[xi][yi]=-1;
push(s,e);
while(!stempty(s))
{
gettop(s,e);
i=e.i;j=e.j,di=e.di;
if(i==xe&&j==ye)
{
printf("迷宫的一条路径如下: \n");
k=0;
while(!stempty(s))
{
pop(s,e);
path[k++]=e;
}
while(k>=1)
{
k--;
printf("(%d,%d)",path[k].i,path[k].j);
}
printf("\n");
destroyst(s);
return true;
}
find=false;
while(di<4&&!find)
{
di++;
switch(di)
{
case 0:il=i-1;jl=j;break;
case 1:il=i;jl=j+1;break;
case 2:il=i+1;jl=j;break;
case 3:il=i;jl=j-1;break;
}
if(mg[il][jl]==0)
find=true;
}
if(find)
{
s->data[s->top].di=di;
e.i=i;
e.j=j;
e.di=-1;
push(s,e);
mg[il][jl]=-1;
}
else
{
pop(s,e);
mg[e.i][e.j]=0;
}
destroyst(s);
return false;
}
}
int main()
{
if(!mgpath(1,1,m,n))
printf("无解");
return 1;
}
运行结果及报错内容
我的解答思路和尝试过的方法
看了十几遍了,一直找不出错误的原因,求各位帮助帮助