64,654
社区成员
发帖
与我相关
我的任务
分享
迷宫的路径如下图:
21313333
21313113
21311133
21222221
22211122
#include <stdio.h>
#include <stdlib.h>
struct stackNode
{
int x;
int y;
struct stackNode *next;
};
typedef struct stackNode stacklist;
typedef stacklist *link;
link path = NULL;//路径栈指针 //
link push(link stack,int x,int y)//入栈
{
link newNode;
newNode = (link) malloc(sizeof(stacklist));
if(!newNode)
{
printf("分配内存失败!");
return NULL;
}
newNode->x = x;
newNode->y = y;
newNode->next = stack;
stack = newNode;
return stack;
}
link pop(link stack,int *x,int *y)//出栈
{
link top;
if(stack!= NULL)
{
top = stack;
stack = stack->next;
*x = stack->x;//是否应该改成top->x?
*y = stack->y;
free(top);
return stack;
}
else
*x = -1;
}
int main()
{
int maze[7][10]=//迷宫最外面即数组最外一层全部为1表示已经是外面了0表示能穿过,1表示柱子不能走
{
1,1,1,1,1,1,1,1,1,1,
1,0,1,0,1,0,0,0,0,1,
1,0,1,0,1,0,1,1,0,1,
1,0,1,0,1,1,1,0,0,1,
1,0,1,0,0,0,0,0,1,1,
1,0,0,0,1,1,1,0,0,1,
1,1,1,1,1,1,1,1,1,1
};
int i,j;
int x = 5;
int y = 8;//迷宫出口为左下角a[1][1],入口为右下角a[5][8]
while ( x!=1||y!=1 )
{
maze[x][y] =2;//2表示走过的路
if(maze[x-1][y] <=0)//向上走
{
x = x-1;
path = ::push (path,x,y);//系统说这里形参不配,为什么?
}
else
if( maze[x+1][y] <=0)//向下
{
x =x+1;
path = push(path,x,y);
}
else
if(maze[x][y-1] <=0)//向左
{
y = y-1;
path = push(path,x,y);
}
else
if(maze[x][y+1] <=0)//向右
{
y = y+1;
path = push(path,x,y);
}
else
{
maze[x][y] =3;//3表示绝路要回溯
path = pop(path,&x,&y);
}
}
maze[x][y] = 2;
printf("迷宫的路径如下图:\n");
for(i = 1;i <6;i++)
{
for(j=1;j <9;j++)
printf("%d",maze[i][j]);
printf("\n");
}
return 0;
}
link path = NULL;//路径栈指针 //