#include <stdio.h>
#define MAX_STACK_SIZE 64
#define MAZE_SIZE 7
#define EXIT_ROW 5
#define EXIT_COL 5
struct element
{
int row;
int col;
int dir;
};
struct offset
{
int vert;
int hori;
};
char move_str[] = { 'N', 'E', 'S', 'W' };
int maze[MAZE_SIZE][MAZE_SIZE] = {
1,1,1,1,1,1,1,
1,0,1,1,1,1,1,
1,0,0,0,0,1,1,
1,0,1,1,1,1,1,
1,0,1,0,0,0,1,
1,0,0,0,1,0,1,
1,1,1,1,1,1,1,
};
offset move[] =
{
{-1,0}, {0,1}, {1,0}, {0,-1}
};
int mark[MAZE_SIZE][MAZE_SIZE] = {0};
element stack[MAX_STACK_SIZE];
int top = 0;
void Path()
{
bool found = false;
int row = 0, col = 0, dir = 0;
int next_row = 0, next_col = 0, next_dir = 0;
while( top > -1 && !found )
{
row = stack[top].row;
col = stack[top].col;
dir = stack[top].dir;
if( dir > 3 )
{
mark[row][col] = 0;
--top;
++stack[top].dir;
continue;
}
next_row = row + move[dir].vert;
next_col = col + move[dir].hori;
if( next_row == EXIT_ROW && next_col == EXIT_COL )
{
found = true;
++top;
stack[top].row = next_row;
stack[top].col = next_col;
}
else if( !maze[next_row][next_col] && !mark[next_row][next_col] )
{
++top;
stack[top].row = next_row;
stack[top].col = next_col;
stack[top].dir = 0;
mark[next_row][next_col] = 1;
}
else
{
++stack[top].dir;
}
}
if( found )
{
for( int i = 0; i < MAZE_SIZE; ++i )
{
for( int j = 0; j < MAZE_SIZE; ++j )
{
printf("%d ", maze[i][j]);
}
printf("\n");
}
for( int i = 0; i <= top; ++i )
{
printf("(%d, %d, %c)\n", stack[i].row, stack[i].col, move_str[stack[i].dir]);
}
}
}
int main(int argc, char **argv)
{
mark[1][1] = 1;
stack[0].row = 1;
stack[0].col = 1;
stack[0].dir = 0;
Path();
return 0;
}
走迷宫-栈的使用
最新推荐文章于 2022-02-25 19:38:17 发布