求助,超出内存
迷宫有一个入口,一个出口。一个人从入口走进迷宫,目标是找到出口。阴影部分和迷宫的外框为墙,每一步走一格,每格有四个可走的方向,探索顺序为:南、东、北、西。 输入:输入迷宫数组
输出:若有解,输出从入口到出口的一条路径,否则输出 there is no solution!
例(上图所示的迷宫数组)
输入
4 4
0 0 1 0
0 1 0 1
0 0 0 0
0 1 0 0
输出
<1,1> <2,1> <3,1> <3,2> <3,3> <4,3> <4,4>
#include <stdio.h>
#include <stdlib.h>
#define n 100
#define m 100
typedef struct node
{int row;
int col;
struct node *next;
}mlink;
mlink *stack;
int mazepath()
{int maze[n][m],i,j,x1,y1,x2,y2,a,b;
mlink *p;
scanf("%d %d\n",&a,&b);
for(i=0;i<a;i++)
{for(j=0;j<b;j++)
{scanf("%d",&maze[i][j]);}
}
x1=0,y1=0;
x2=a;y2=b;
stack=NULL;
p=(mlink*)malloc(sizeof(mlink));
p->row =x1;p->col =y1;
p->next =stack;
stack=p;
maze[stack->row][stack->col]=1;
while((stack->row!=x2)||(stack->col!=y2)||(stack!=NULL))
{if(maze[stack->row +1][stack->col]==0)
{p=(mlink*)malloc(sizeof(mlink));
p->row =stack->row +1;p->col =stack->col ;
p->next =stack;stack=p;
maze[stack->row ][stack->col ]=1;
}
else if(maze[stack->row][stack->col+1]==0)
{p=(mlink*)malloc(sizeof(mlink));
p->row =stack->row ;p->col =stack->col+1 ;
p->next =stack;stack=p;
maze[stack->row ][stack->col ]=1;
}
else if(maze[stack->row -1][stack->col ]==0)
{p=(mlink*)malloc(sizeof(mlink));
p->row =stack->row -1;p->col =stack->col ;
p->next=stack;stack=p;
maze[stack->row ][stack->col ]=1;
}
else if(maze[stack->row ][stack->col -1]==0)
{p=(mlink*)malloc(sizeof(mlink));
p->row =stack->row ;p->col =stack->col-1 ;
p->next =stack;stack=p;
maze[stack->row ][stack->col ]=1;
}
else {p=stack;stack=stack->next ;free(p);}
}
if(stack==NULL) return(0);
else return(1);
}
void main()
{int i=0;
mlink *p;
i=mazepath();
if(i=1)
{p=stack;
while(p!=NULL)
{printf("%d,%d",p->row ,p->col );
p=p->next ;
}
printf("\n");
}
else printf("there is no solution!\n");
}