ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

C++采用栈和BFS算法求解迷宫问题

2026/9/19 0:44:15 拓冰建站 浏览量
C++采用栈和BFS算法求解迷宫问题

步骤 1: 定义迷宫

首先,我们需要定义迷宫。我们可以使用二维数组来表示迷宫,其中 1 1 1 表示可通过的路径, 0 0 0 表示障碍物。例如,下面是一个 5 × 5 5\times5 5×5 的迷宫示例:

int maze[5][5] = {{1, 0, 1, 1, 1},{1, 1, 1, 0, 1},{0, 0, 0, 1, 0},{1, 1, 1, 1, 1},{1, 1, 1, 0, 0}
};

如果需要手动输入,则写出如下代码:

int row, col;
cin >> row >> col;
for (int i = 0; i < row; i++)
{for (int j = 0; j < row; j++){cin >> maze[i][j];}
}

步骤 2: 定义迷宫中的点

我们需要定义一个结构体(struct)来表示迷宫中的点。结构体包含 x x x y y y 坐标以及父节点的 x x x y y y 坐标。例如:

struct Node
{int x;int y;int px;int py;
};

步骤 3: 检查点的有效性

我们需要一个函数来检查点是否在迷宫范围内且没有障碍物。如果点有效,那么返回 true,否则返回 false。可以使用下面的代码实现:

bool isValid(int x, int y, int row, int col, int maze[][105])
{// 检查坐标是否在迷宫范围if (x >= 0 && x < row && y >= 0 && y < col){// 检查该点是否可通行return (maze[x][y] == 1);}else{return false;}
}

步骤 4: 打印路径

在找到目标点后,我们需要打印找到的路径。我们可以使用一个栈来存储路径,然后按顺序打印路径上的每个点。下面是打印路径的代码:

void printPath(int row, int col, int maze[][105], Node dest)
{stack<Point> path;int x = dest.x;int y = dest.y;while (x != -1 && y != -1){path.push(Point {x, y, -1, -1});int tempx = x;int tempy = y;x = dest.px;y = dest.py;dest.px = tempx;dest.py = tempy;}while (!path.empty()){Point point = path.top();path.pop();cout << "(" << point.x << ", " << point.y << ") ";}cout << endl;
}

步骤 5: 使用 BFS 算法解决迷宫问题

我们可以使用 B F S BFS BFS 算法来解决迷宫问题。我们使用一个队列来存储待访问的点,并使用一个二维数组来记录已访问的点。首先,将起点入队并标记为已访问,然后开始循环直到队列为空。在每次循环中,从队列中取出一个点,检查其8个方向上的邻居点是否有效,并将有效的邻居点入队并标记为已访问。如果找到目标点,则打印路径并结束循环。下面是解决迷宫问题的代码:

void solveMaze(int row, int col, int maze[][105], Node src, Node dest)
{bool visited[105][105];for (int i = 0; i < row; i++){for (int j = 0; j < col; j++){visited[i][j] = false;}}queue<Point> q;q.push(src);visited[src.x][src.y] = true;bool foundDest = false;while (!q.empty()){Point curr = q.front();q.pop();int x = curr.x;int y = curr.y;if (x == dest.x && y == dest.y){foundDest = true;printPath(maze, curr);break;}// 以8个方向进行BFS遍历if (isValid(x+1, y, row, col, maze) && !visited[x+1][y]){q.push(Point {x+1, y, x, y});visited[x+1][y] = true;}if (isValid(x-1, y, row, col, maze) && !visited[x-1][y]){q.push(Point {x-1, y, x, y});visited[x-1][y] = true;}if (isValid(x, y+1, row, col, maze) && !visited[x][y+1]){q.push(Point {x, y+1, x, y});visited[x][y+1] = true;}if (isValid(x, y-1, row, col, maze) && !visited[x][y-1]){q.push(Point {x, y-1, x, y});visited[x][y-1] = true;}if (isValid(x+1, y+1, row, col, maze) && !visited[x+1][y+1]){q.push(Point {x+1, y+1, x, y});visited[x+1][y+1] = true;}if (isValid(x-1, y+1, row, col, maze) && !visited[x-1][y+1]){q.push(Point {x-1, y+1, x, y});visited[x-1][y-1] = true;}if (isValid(x+1, y-1, row, col, maze) && !visited[x+1][y-1]){q.push(Point {x+1, y-1, x, y});visited[x+1][y-1] = true;}if (isValid(x-1, y-1, row, col, maze) && !visited[x-1][y-1]){q.push(Point {x-1, y-1, x, y});visited[x-1][y-1] = true;}}if (!foundDest){cout << "迷宫无解" << endl;}
}