利用棧走迷宮
阿新 • • 發佈:2019-01-24
/*棧實現走迷宮
棧和遞迴思路有些不一樣,遞迴考慮一個結點的所有可能,不去觸碰下一個結點。
棧的話迴圈之前的初始條件要和下次迴圈一致,並且會用到提前判斷,提前繼續迴圈,
通過取棧頂達到假回溯效果,進到迴圈裡的結點雖然還是一樣,但是沒有記錄狀態了
遞迴的回溯狀態和之前是完全一樣的(在判斷條件的執行流中沒有出來),因此有試探-回溯的做法
*/
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;
}