C语言 老鼠走迷宫

来源:百度知道 编辑:UC知道 时间:2024/09/22 08:24:52
死循环了,哪错了

#include <stdio.h>
#define M 5
#define N 6

int flag=0;
int a[M][N]={{0,0,0,1,0,0},{0,1,0,0,0,0},{0,1,1,1,1,0},{0,0,0,0,0,1},{1,0,1,1,0,0}};

void search(x,y)
{
a[x][y]=2;

if ((x==M-1)&&(y==N-1)) flag=1;

if ((flag!=1)&&(y!=N-1) && (a[x][y+1]==0)) search(x,y+1);
if ((flag!=1)&&(x!=M-1) && (a[x+1][y]==0)) search(x+1,y);
if ((flag!=1)&&(y!=0 ) && (a[x][y-1]==0)) search(x,y-1);
if ((flag!=1)&&(x!=0 ) && (a[x-1][y]==0)) search(x-1,y);

if (flag!=1) a[x][y]==1;
}

main()
{
int i,j;

search(0,0);

for(i=0;i<M;i++)
{
for(j=0;i<N;j++)
printf("%d",a[i][j]);
printf("\n");
}

}

每走过一个点,要把走过的点的坐标由0改成其他值,如2,这样就不会在朝回走,造成循环了,嘿嘿,我写的如下:
#include<stdio.h>
#include<stdlib.h>
#define M 15
#define N 15
struct mark //定义迷宫内点的坐标类型
{
int x;
int y;
};

struct Element //"恋"栈元素,嘿嘿。。
{
int x,y; //x行,y列
int d; //d下一步的方向
};

typedef struct LStack //链栈
{
Element elem;
struct LStack *next;
}*PLStack;

/*************栈函数****************/

int InitStack(PLStack &S)//构造空栈
{
S=NULL;
return 1;
}

int StackEmpty(PLStack S)//判断栈是否为空
{
if(S==NULL)
return 1;
else
return 0;
}

int Push(PLStack &S, Element e)//压入新数据元素
{
PLStack p;
p=(PLStack)malloc(sizeof(LStack));
p->elem=e;
p->next=S;
S=p;
return 1;
}

int Pop(PLStack &S,Element &e) //栈顶元素出栈
{