给定一个迷宫。如何走出去?最近有看看栈和队列
就想用栈和队列实现,写了半天,终于写出来了。。。
// 0 代表此路可走 1 代表此路不通
// 只能走四个方向,即上下左右
//周围的 111... 代表围墙。。
#include<stdio.h>
#include<stdlib.h>
#define mac 100 //定义栈的大小限制
typedef struct
{
short int row; //行
short int col; //列
short int dir; //方向
}element;
element stack[mac];
typedef struct
{
short int vert; //垂直方向
short int horiz; //水平方向
}offset;
offset move[4] = {{-1,0},{0,1},{1,0},{0,-1}}; //4个方向的偏移量
int top = -1;
int maze[10][10] =
{
{1,1,1,1,1,1,1,1,1,1},
{1,0,1,0,0,0,1,1,0,1},
{1,0,0,1,1,0,0,1,1,1},
{1,1,0,0,0,1,1,0,0,1},
{1,0,0,0,0,0,0,0,0,1},
{1,1,0,0,0,0,1,1,1,1},
{1,1,1,0,0,0,0,0,0,1},
{1,1,1,1,0,0,0,0,1,1},
{1,1,1,0,0,0,0,0,0,1},
{1,1,1,1,1,1,1,1,1,1}
};
int mark[10][10];
#define enter_row 1
#define enter_col 1
#define exit_row 8
#define exit_col 8
void path();
void push(int *top,element a)
{
++(*top);
if(*top <= mac - 1)
stack[*top] = a;
else
{
printf("over flow!!!\n");
exit(1);
}
}
element pop(int *top)
{
if(*top >= 0)
return (stack[(*top)--]);
else
{
printf("stack overflow!!!\n");
exit(1);
}
}
element gettop(int top)
{
if(top>=0)return (stack[top]);
else
{
printf("stack undefined.\n");
exit(1);
}
}
void path()
{
int i,j;
int row,col,next_row,next_col;
int dir,found = 0; //found 标记参数 0代表未访问 1代表访问
element position;
for(i=0;i<10;i++)
for(j=0;j<10;j++)
mark[i][j] = 0;
mark[1][1] = 1; //初始化标记地图
top = 0;
stack[0].row = enter_row; //将入口推进栈里面
stack[0].col = enter_col;
stack[0].dir = 0;
while(top>-1&&!found){
position = gettop(top); //获取栈顶元素
row = position.row;
col = position.col;
dir = position.dir;
while(dir<4&&!found){ //没有发现出口
next_row = row + move[dir].vert;
next_col = col + move[dir].horiz; //探寻下一个方向,首先是上面
if(next_row == exit_row && next_col == exit_col)
found = 1; //找到出口
//如果找到下一个可以走的地方将下一个地方作为新的入口
else if(!maze[next_row][next_col] && !mark[next_row][next_col]){
mark[next_row][next_col] = 1;
position.row = next_row; position.col = next_col;
position.dir = ++dir;
push(&top,position);
row = next_row; col = next_col; dir = 0;
}
//找不到,重新试探方向
else ++dir;
}
//再找不到说明死路,退栈
if(!found)
position = pop(&top);
}
//找到的话就输出寻找的痕迹 1 为探索过
if(found == 1){
mark[8][8]=1;
printf("探索过的地方为:\n");
for(i=0;i<10;i++)
{
for(j=0;j<10;j++)
printf("%-2d ",mark[i][j]);
printf("\n");
}
}
if(found == 1)
{
printf(" 行走的路径为:\n");
printf(" 步数 行号 列号.\n");
for(i=0;i<top;i++)
printf("%5d %5d %5d\n",i+1,stack[i].row,stack[i].col);
printf("%5d %5d %5d\n",i+1,exit_row,exit_col);
}
else
printf("the maze don't have a path.\n");
}
int main()
{
path();
return 0;
}