栈的妙用-实现迷宫问题
for(; i >
to store the used place*/
int mark[NEW_MAZE_ROWS][NEW_MAZE_COLS];
void mark_init()
{
int i = 0,j = 0;
for(i = 0; i < NEW_MAZE_ROWS ; ++ i)
for(j = 0; j < NEW_MAZE_COLS ; ++ j)
mark[i][j] = 0;
}
intmark_stack_size(int maze[NEW_MAZE_ROWS][NEW_MAZE_COLS])
{
int i = 0,j = 0;
int size = 0;
for(i = 0; i < NEW_MAZE_ROWS; ++ i)
for (j = 0; j < NEW_MAZE_COLS ; ++ j)
{
if(!maze[i][j])
size ++;
}
return size;
}
coordinate nextposition(element a,int dir)
{
coordinate b;
b.col = a.col + move[dir].horiz;
b.row = a.row + move[dir].vert;
return b;
}
int maze_out()
{
element temp;
coordinatenextp;
/*Test the stack is not empty*/
while(top >= 0)
{
/*pop a element*/
temp = *(stack+top);
top --;
/*find on eight directions*/
while(temp.dir < 8)
{
/*get the possible next positions*/
nextp = nextposition(temp,temp.dir);
/*next direction*/
temp.dir ++;
/*success conditions*/
if(nextp.row == EXIT_ROW &&
nextp.col == EXIT_COL)
{
/*save current position*/
stack[++top] = temp;
/*save the exit pointion*/
stack[++top].row = EXIT_ROW;
stack[top].col = EXIT_COL;
stack[top].dir = 0;
/*exit*/
return 1;
}
/*the new position is ok and does not wake*/
if(maze[nextp.row][nextp.col] ==0 &&
mark[nextp.row][nextp.col] == 0)
{
/*mark means that this way has been waked*/
mark[nextp.row][nextp.col] = 1;
/*
*push a element in stack
*save current position and direction
*if this way is failed, used to this position to start new way.
*/
stack[++top] = temp;
/*go to the new position as current position*/
temp.row = nextp.row;
temp.col =nextp.col;
temp.dir = 0;
}
}
}
/*failed*/
return 0;
}
int main()
{
int i = 0;
/*inital the mark array*/
mark_init();
initial_move();
/*create stack*/
stack = (element*)malloc(mark_stack_size(maze)*sizeof(element));
/*if failed*/
if(stack == NULL)
return 0;
/*push a element in stack*/
top ++;
(stack+top)->col = 1;
(stack+top)->row = 1;
(stack+top)->dir = 0;
if(maze_out())
{
while(i <= top)
{
printf("(%d,%d,%d)",stack[i].row,stack[i].col,stack[i].dir);
i ++;
}
// printf("(%d,%d)",EXIT_ROW,EXIT_COL);
}
/*free the memory*/
free(stack);
/*point to the NULL*/
stack = NULL;
return 1;
}
测试结果:
在迷宫问题中,栈主要实现了对满足条件坐标以及方向值(0-7,分别表示一个具体的方向)的动态保存能够保证路劲的一致性,也就是先入后出的特性。
堆栈迷宫问 相关文章:
- Windows CE 进程、线程和内存管理(11-09)
- RedHatLinux新手入门教程(5)(11-12)
- uClinux介绍(11-09)
- openwebmailV1.60安装教学(11-12)
- Linux嵌入式系统开发平台选型探讨(11-09)
- Windows CE 进程、线程和内存管理(二)(11-09)