#include
#include
#define M 6 //迷宫的实际行
#define N 8 //迷宫的实际列
#define MAXSIZE 64 //栈大小
typedef struct
{
int x;
int y;
}item_t;
typedef struct
{
int x; //当前点的坐标
int y;
int z; //移动方向
}coord_t;
typedef struct
{
int x[MAXSIZE-1];
int y[MAXSIZE-1];
int z[MAXSIZE-1];
int top ;
}stack_t;
//迷宫数组
int maze[M+2][N+2] =
{// 0 1 2 3 4 5 6 7 8 9
{ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },// 0
{ 1, 0, 1, 1, 1, 0, 1, 1, 1, 1 },// 1
{ 1, 1, 0, 1, 0, 1, 1, 1, 1, 1 },// 2
{ 1, 0, 1, 0, 0, 0, 0, 0, 1, 1 },// 3
{ 1, 0, 1, 1, 1, 0, 1, 1, 1, 1 },// 4
{ 1, 1, 0, 0, 1, 1, 0, 0, 0, 1 },// 5
{ 1, 0, 1, 1, 0, 0, 1, 1, 0, 1 },// 6
{ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } // 7
};
//移动方向
item_t move[8] = {{0,1},{1,1},{1,0},{1,-1},{0,-1},{-1,-1},{-1,0},{-1,1}};
stack_t* init_stack(void)
{
stack_t* st = (stack_t *)malloc(sizeof(stack_t));
if(st == NULL)
{
printf("malloc error\n");
return NULL;
}
st->top = -1;
return st;
}
int empty_stack(stack_t* st)
{
if(st->top == -1)
return 1;
else
return 0;
}
int full_stack(stack_t* st)
{
if(st->top > MAXSIZE -1)
return 1;
else
return 0;
}
int push_stack(stack_t* st, coord_t cor)
{
if(full_stack(st))
{
printf("stack full.\n");
return 0;
}
st->top ++ ;
st->x[st->top] = cor.x ;
st->y[st->top] = cor.y ;
st->z[st->top] = cor.z ;
return 1;
}
int pop_stack(stack_t* st, coord_t* cor)
{
if(empty_stack(st))
{
printf("stack empty.\n");
return 0;
}
cor->x = st->x[st->top] ;
cor->y = st->y[st->top] ;
cor->z = st->z[st->top] ;
st->top-- ;
return 1;
}
void loop_stack(stack_t* st)
{
coord_t cor;
printf("输出出栈的数据:\n");
while(!empty_stack(st))
{
pop_stack(st, &cor);
printf("x=%d y=%d z=%d\n",cor.x, cor.y, cor.z);
}
}
int main(void)
{
int x,y,z,i,j;
coord_t cor;
stack_t* st = init_stack() ;
cor.x = 1;
cor.y = 1;
cor.z = -1; //入口
push_stack(st, cor); //入栈
printf("开始找路...\n");
while(!empty_stack(st)) //如果栈非空
{
pop_stack(st, &cor); //出栈 当前坐标
x = cor.x;
y = cor.y;
z = cor.z + 1; //顺时针方向 试探
while(z<8)
{
i = x + move[z].x; //试探方向
j = y + move[z].y;
if(maze[i][j] == 0) //如果有路
{
cor.x = x; //保存上一个点的坐标
cor.y = y;
cor.z = z;
push_stack(st, cor);
x = i; //
y = j;
maze[i][j] = -1; //标记一下此处走过
if((x==M) && (y==N)) //到达出口
{
cor.x = x; //保存出口坐标退出
cor.y = y;
cor.z = z;
push_stack(st, cor);
goto loop;
}
else
z = 0;
}
else
{
z++ ;
}
}
}
loop:
loop_stack(st);
free(st);
return 0;
}