/*栈实现走迷宫
栈和递归思路有些不一样,递归考虑一个结点的所有可能,不去触碰下一个结点。
栈的话循环之前的初始条件要和下次循环一致,并且会用到提前判断,提前继续循环,
通过取栈顶达到假回溯效果,进到循环里的结点虽然还是一样,但是没有记录状态了
递归的回溯状态和之前是完全一样的(在判断条件的执行流中没有出来),因此有试探-回溯的做法
*/
int passMaze(int maze[ROW][COL], Position entry, Stack* path) {
//合法入口
if (maze[entry.x][entry.y] != 1) {
return path;
}
pushBack(path, entry);
while (!isEmpty(path)) {
Position cur = top(path);
maze[cur.x][cur.y] = 2;
if ((cur.x == ROW - 1 || cur.y == COL - 1 || cur.x == 0 || cur.y == 0)&& !(cur.x ==entry.x && cur.y ==entry.y)) {
break;
}
else {
int dir[4][2] = { { -1,0 },{ 1 ,0 },{ 0 , -1 },{ 0, 1 } };
int i;
for (i = 0; i < 4; i++) {
int xNext = cur.x + dir[i][0];
int yNext = cur.y + dir[i][1];
Position next;
next.x = xNext, next.y = yNext;
if (maze[next.x][next.y] == 1) {
pushBack(path, next);
break;
}
}
if (i != 4) {
continue;
}
pop(path);
}
}
return !isEmpty(path);
}
//递归走迷宫,单纯的dfs是不能记录有序路径的
int passMazeR(int maze[ROW][COL], Position cur, Position entry, Stack* path)
{
//不合法
if (maze[cur.x][cur.y] != 1) {
return 0;
}
//出口
if ((cur.x == ROW - 1 || cur.y == COL - 1 || cur.x == 0 || cur.y == 0)
&& !(cur.x == entry.x && cur.y == entry.y))
{
pushBack(path, cur);
return 1;
}
maze[cur.x][cur.y] = 2;
pushBack(path, cur);
//四方
int dir[4][2] = { { -1,0 },{ 1 ,0 },{ 0 , -1 },{ 0, 1 } };
int i;
for (i = 0; i < 4; i++) {
int xNext = cur.x + dir[i][0];
int yNext = cur.y + dir[i][1];
Position next;
next.x = xNext, next.y = yNext;
if (passMazeR(maze, next, entry, path)) {
return 1;
}
}
pop(path);
maze[cur.x][cur.y] = 1;
return 0;
}
利用栈走迷宫
最新推荐文章于 2023-10-02 22:34:23 发布