#include <stdio.h>
#include <stdlib.h>
#define TRUE 1
#define FALSE 0
#define step 54
#define EXIT_ROW 8
#define EXIT_COL 5
struct element {
short int row;
short int col;
short int dir;
};
typedef struct element element;
element stack[step];
int top;
element push(element item){
stack[++top] = item;
}
element pop(){
return stack[top--];
}
struct hehe {
int vert;
int horiz;
};
typedef struct hehe hehe;
hehe move[8]={{-1,0},{-1,1},{0,1},{1,1},{1,0},{1,-1},{0,-1},{-1,-1}};
int mark[9][6]={0};
/*迷宫矩阵,0代表可以走,1代表障碍*/
int maze[9][6]={{0,0,0,0,0,1},{1,1,1,1,1,0},{1,0,0,0,0,1},{0,1,1,1,1,1},{1,0,0,0,0,1},{1,1,1,1,1,0},{1,0,0,0,0,1},{0,1,1,1,1,1},{1,0,0,0,0,0}};
//int maze[1][6]={0};
void path(void)
{ //output a path through the maze if such a path exists
int i, row, col, nextRow, nextCol, dir, found=FALSE;
element position;
//mark[1][1] = 1;
top = 0;
stack[0].row = 0;
stack[0].col = 0;
stack[0].dir = 0;
while (top>-1 && !found) {
position = pop();
row = position.row; col = position.col;
dir = position.dir;
while (dir<8 && !found) {
//move in direction dir
nextRow = row + move[dir].vert;
nextCol = col + move[dir].horiz;
if ((nextRow==EXIT_ROW)&&(nextCol==EXIT_COL))
found = TRUE;
else if (!maze[nextRow][nextCol] && !mark[nextRow][nextCol] && nextRow>=0 && nextRow<9 && nextCol>=0 &&nextCol<6) {
//必须加上边界条件,否则你不知道nextRow或nextCol在数组范围外时会取出什么数字来,有可能就回不到正路上来了
mark[nextRow][nextCol] = 1;
position.row = row; position.col = col;
position.dir = ++dir;
push(position);
row = nextRow; col = nextCol;
dir = 0;
}
else ++dir;
}
}
if (found) {
printf("the path is:\n");
printf("row col:\n");
for (i=0; i<=top; i++)
printf("%2d%5d\n", stack[i].row, stack[i].col);
printf("%2d%5d\n", row, col);
printf("%2d%5d\n", EXIT_ROW, EXIT_COL);
}
else printf("The maze does not have a path\n");
}
void main()
{
int i,j;
for(i=0;i<9;i++){
for(j=0;j<6;j++){
printf("%d ",maze[i][j]);
}
printf("\n");
}
path();
system("pause");
}
堆栈实现迷宫出路(C语言)
最新推荐文章于 2023-06-16 13:41:50 发布