迷宮求解
其實問題很容易理解的,就是題目給出一個迷宮,入口位置和出口位置,求解該迷宮是否能夠走通。利用順序棧,逐個位置進行探索。
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的引用形式編譯器會報錯,但是很多書上是這樣寫的,於是改成了指針作爲函數的參數。
這個迷宮做了還蠻長時間的,因爲彎彎繞繞的老是搞不清楚,看了很多參考資料,最後一步一步調試,在紙上慢慢抄慢慢調。沉住氣,堅持,你做的遠遠不夠。