给一个二维列表,表示迷宫(0表示通道,1表示围墙)。给出算法,求一条走出迷宫的路径。
1代表墙,0代表路,图示如下:
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#define max 100
typedef struct Dircet
{
int x;
int y;
}Dircet;
typedef struct Coordinate
{
int x;
int y;
}coordinate;
typedef struct Stack
{
coordinate* top;
coordinate* base;
}stack;
void mcreat(stack& s)//初始化 栈
{
s.base = (coordinate*)malloc(max * sizeof(coordinate));
if (!s.base)
{
printf("ERROR!\n");
return;
}
s.top = s.base;
}
void mpush(stack& s, coordinate e)//入栈
{
if (s.top - s.base == max)
printf("栈满\n");
else
{
*s.top = e;
s.top++;
}
}
void mpop(stack& s, coordinate &e)//出栈
{
if (s.top - s.base == 0)
printf("栈空\n");
else
{
s.top--;
e = *s.top;
}
}
void inputarea(stack s)//输出路径坐标
{
coordinate e;
if (!s.base)
printf("不存在\n");
else
{
while (s.top != s.base)
{
mpop(s, e);
printf("(%d,%d) ",e.x,e.y);
}
printf("\n");
}
}
int judge(stack s) //判断是否栈空
{
if (s.top - s.base == 0)
return 1;
else
return 0;
}
void findpath(int maze[10][10], stack &s, Dircet dircet[4])//迷宫的路径函数
{
int x, y,di=0;
int line, row;
coordinate temp;
maze[1][1] = -1;
temp = {1,1};
mpush(s, temp);
while (!judge(s))
{
di = 0;
mpop(s, temp);
while (di < 4)
{
row = temp.x + dircet[di].x;
line = temp.y + dircet[di].y;
if (maze[row][line] == 0)
{
mpush(s, temp);
maze[row][line] = -1;
temp.x = row;
temp.y = line;
di = 0;
if (row == 8 && line == 8)
return;
}
else
di++;
}
}
}
int main()
{
stack s;
Dircet dircet[4] = { {0,1},{1,0},{0,-1},{-1,0} };//行走的四个方向移动的坐标
int maze[10][10] = {
{1,1,1,1,1,1,1,1,1,1},
{1,0,0,1,0,0,0,1,0,1},
{1,0,0,1,0,0,0,1,0,1},
{1,0,0,0,0,1,1,0,0,1},
{1,0,1,1,1,0,0,0,0,1},
{1,0,0,0,1,0,0,0,0,1},
{1,0,1,0,0,0,1,0,0,1},
{1,0,1,1,1,0,1,1,0,1},
{1,1,0,0,0,0,0,0,0,1},
{1,1,1,1,1,1,1,1,1,1}
};
mcreat(s);
findpath(maze, s, dircet);
inputarea(s);
return 0;
}