迷宫求解
其实问题很容易理解的,就是题目给出一个迷宫,入口位置和出口位置,求解该迷宫是否能够走通。利用顺序栈,逐个位置进行探索。
CODE:
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100
#define OK 1
#define FAIL 0
#define STACK_INIT_SIZE 10000
typedef int Status;
typedef struct{
int x;
int y;
}PosType;
typedef struct
{
int ord;
PosType seat;
int di;
}SElemType;
typedef struct
{
SElemType *base;
SElemType *top;
int stacksize;
}SqStack;
typedef struct{
PosType seat;
char pass;
int visit;
}MazeType;
void InitStack(SqStack *S)
{
S->base = (SElemType *)malloc(STACK_INIT_SIZE*sizeof(SElemType));
S->top = S->base;
S->stacksize = STACK_INIT_SIZE;
}
void Push(SqStack *S, SElemType e)
{
*(S->top++) = e;
}
void Pop(SqStack *S, SElemType *e)
{
*e = *(--S->top);
}
int EmptyStack(SqStack S)
{
if(S.top == S.base)
return 1;
else
return 0;
}
void NextPos(PosType *seat, int di)
{
if(di == 1)
seat->x = seat->x + 1;
if(di == 2)
seat->y = seat->y - 1;
if(di == 3)
seat->x = seat->x - 1;
if(di ==4)
seat->y = seat->y + 1;
}
SqStack S;
Status MazePath(MazeType maze[][MAXSIZE], PosType start, PosType end) //maze[][n], the first [] indicates it is a pointer
{
SElemType e;
InitStack(&S);
PosType curpos;
curpos = start;
int curstep = 1;
do
{
if((*(*(maze+curpos.x)+curpos.y)).pass == 'p' && (*(*(maze+curpos.x)+curpos.y)).visit == 0)
{
(*(*(maze+curpos.x)+curpos.y)).visit = 1;
e.ord = curstep;
e.seat = curpos;
e.di = 1;
Push(&S,e);
if (curpos.x == end.x && curpos.y == end.y)
return OK;
NextPos(&curpos, 1);
curstep++;
}
else
{
if(!EmptyStack(S))
{
Pop(&S,&e);
while(e.di==4 && !EmptyStack(S))
{
(*(*(maze+e.seat.x)+e.seat.y)).pass = 'b';
Pop(&S,&e);
}
if(e.di<4)
{
e.di++;
Push(&S, e);
NextPos(&e.seat, e.di);
curpos = e.seat;
}
}
}
}while(!EmptyStack(S));
return FAIL;
}
int main()
{
int m, n, i, j;
char c;
PosType start, end;
MazeType maze[MAXSIZE][MAXSIZE];
printf("Please enter the number of lines of the maze: ");
scanf("%d", &m);
printf("Please enter the number of columns of the maze: ");
scanf("%d", &n);
printf("Please enter the maze pattern:\n"); // input format:bbbbbppbbppbbbbb b represents blocked, p represents pass
//getchar();
fflush(stdin);// refresh the buffer
for(i=0; i<m; i++){
for(j=0; j<n; j++){
scanf("%c", &maze[i][j].pass);
maze[i][j].seat.x = i;
maze[i][j].seat.y = j;
maze[i][j].visit = 0;
}
fflush(stdin);
}
printf("Please enter the position of the start point:");
scanf("%d %d", &(start.x), &(start.y));
printf("Please enter the position of the end point:");
scanf("%d %d", &(end.x), &(end.y));
SElemType e;
if(MazePath(maze, start, end)){
printf("There is a path O(∩_∩)O~\n");
while(!EmptyStack(S)){
Pop(&S, &e);
printf("(%d, %d)->", e.seat.x, e.seat.y);
}
}
else
printf("This is a maze you will never get out!");
return 0;
}
- 有一段时间在调试的时候输入总是出现问题,查了一下是scanf()其实是会接收回车在缓冲区的(以前貌似没碰到过这种情况啊),所以加上fflush(stdin)刷新一下缓冲区就好了。
- 最后在输出路径的时候其实是从终点往起点输出的,顺序是反的。
- 形参用&S的引用形式编译器会报错,但是很多书上是这样写的,于是改成了指针作为函数的参数。
这个迷宫做了还蛮长时间的,因为弯弯绕绕的老是搞不清楚,看了很多参考资料,最后一步一步调试,在纸上慢慢抄慢慢调。沉住气,坚持,你做的远远不够。