OpenJudge 迷宫问题 BFS

使用BFS算法寻找迷宫中从起点到终点的最短路径。为记录路径,避免使用STL队列,转而采用自定义一维数组配合头尾指针管理。在遍历过程中,通过节点间的前驱指针,结合栈实现路径回溯。
描述
定义一个二维数组: 

int maze[5][5] = {
0, 1, 0, 0, 0,
0, 1, 0, 1, 0,
0, 0, 0, 0, 0,
0, 1, 1, 1, 0,
0, 0, 0, 1, 0,
};
它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线
输入
一个5 × 5的二维数组,表示一个迷宫。数据保证有唯一解。
输出
左上角到右下角的最短路径,格式如样例所示。
样例输入
0 1 0 0 0
0 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0
样例输出
(0, 0)
(1, 0)
(2, 0)
(2, 1)
(2, 2)
(2, 3)
(2, 4)
(3, 4)

(4, 4)


寻找最短路径,因此用BFS比较好,由于该题需要最短路径所经过的点,故不能使用STL的队列,可以自己设一个一维数组,用头指针和尾指针进行维护。

在每个节点中,设一个指针指向前一个结点,再用栈即可输出。

#include <iostream>
#include <cstdio>
#include <map>
#include <set>
#include <vector>
#include <queue>
#include <stack>
#include <cmath>
#include <algorithm>
#include <cstring>
#include <string>
using namespace std;
#define INF 0x3f3f3f3f
typedef long long LL;
bool v[10][10];
int a[10][10];
int top,rear;
struct node{
    int x;
    int y;
    int steps;
    int t;
};
node q[35];
stack<node> p;
void f(int a,int b)
{
    q[rear].x=a;
    q[rear].y=b;
    q[rear].steps=q[top].steps+1;
    q[rear].t=top;
    rear++;
    v[a][b]=true;
}
void bfs()
{
  while(top<rear){
    if(q[top].x==5&&q[top].y==5){
        while(q[top].t!=-1){
            p.push(q[top]);
            top=q[top].t;
        }
        printf("(0, 0)\n");
        while(!p.empty()){
            printf("(%d, %d)\n",p.top().x-1,p.top().y-1);
            p.pop();
        }
        return;
    }
    int i=q[top].x;
    int j=q[top].y;
    if(!a[i][j-1]&&!v[i][j-1]){
        f(i,j-1);
    }
    if(!a[i][j+1]&&!v[i][j+1]){
        f(i,j+1);
    }
    if(!a[i-1][j]&&!v[i-1][j]){
        f(i-1,j);
    }
    if(!a[i+1][j]&&!v[i+1][j]){
        f(i+1,j);
    }
    top++;
}
}
int main()
{
    for(int i=0;i<=6;i++){
        a[0][i]=a[6][i]=a[i][0]=a[i][6]=1;
    }
    for(int i=1;i<=5;i++){
        for(int j=1;j<=5;j++){
            scanf("%d",&a[i][j]);
        }
    }
    top=rear=0;
    memset(v,false,sizeof(v));
    q[rear].x=1;
    q[rear].y=1;
    q[rear].steps=1;
    q[rear].t=-1;
    rear++;
    v[1][1]=true;
    bfs();
    return 0;
}



使用广度优先搜索(BFS)和深度优先搜索(DFS)解决迷宫问题是常见的图搜索算法应用。 ### BFS解决迷宫问题 BFS采用逐层扩展的方式,先访问当前节点的所有邻居节点,再逐层向外扩展,适合搜索最短可行路径,且第一次找到的可行解一定是最短路径 [^2][^4]。 解决步骤如下: 1. 定义迷宫类,包含迷宫的行数、列数和一个二维的字符数组迷宫。 2. 实现`bfs`函数,用于进行广度优先搜索,以找到从起点到终点的路径。 3. 在`main`函数中,创建一个迷宫对象,调用`bfs`函数来解决迷宫问题。 示例代码如下: ```python from collections import deque # 定义迷宫类 class Maze: def __init__(self, rows, cols, maze): self.rows = rows self.cols = cols self.maze = maze def bfs(self, start, end): # 定义四个方向:上、下、左、右 directions = [(-1, 0), (1, 0), (0, -1), (0, 1)] # 初始化队列 queue = deque([(start, [start])]) # 记录已访问的节点 visited = set([start]) while queue: (x, y), path = queue.popleft() if (x, y) == end: return path for dx, dy in directions: new_x, new_y = x + dx, y + dy if 0 <= new_x < self.rows and 0 <= new_y < self.cols and self.maze[new_x][new_y] == 0 and (new_x, new_y) not in visited: new_path = path + [(new_x, new_y)] queue.append(((new_x, new_y), new_path)) visited.add((new_x, new_y)) return None # 示例迷宫 maze = [ [0, 1, 0, 0, 0], [0, 1, 0, 1, 0], [0, 0, 0, 0, 0], [0, 1, 1, 1, 0], [0, 0, 0, 1, 0] ] m = Maze(5, 5, maze) start = (0, 0) end = (4, 4) path = m.bfs(start, end) if path: print("最短路径:", path) else: print("未找到路径") ``` ### DFS解决迷宫问题 DFS是一种递归的搜索算法,其核心思想是沿着一个分支尽可能深入地搜索,直到达到最深的节点,然后再回溯到上一层,继续探索其他分支,适合搜索所有的可行路径,但第一次找到的可行解不一定是最短路径 [^2][^4]。 解决步骤如下: 1. 定义迷宫的二维数组。 2. 实现`dfs`函数,用于进行深度优先搜索。 3. 在`main`函数中,调用`dfs`函数来解决迷宫问题。 示例代码如下: ```python # 定义迷宫 maze = [ [0, 1, 0, 0, 0], [0, 1, 0, 1, 0], [0, 0, 0, 0, 0], [0, 1, 1, 1, 0], [0, 0, 0, 1, 0] ] rows = 5 cols = 5 start = (0, 0) end = (4, 4) # 记录所有可行路径 all_paths = [] def dfs(x, y, path, visited): if (x, y) == end: all_paths.append(path[:]) return directions = [(-1, 0), (1, 0), (0, -1), (0, 1)] for dx, dy in directions: new_x, new_y = x + dx, y + dy if 0 <= new_x < rows and 0 <= new_y < cols and maze[new_x][new_y] == 0 and (new_x, new_y) not in visited: path.append((new_x, new_y)) visited.add((new_x, new_y)) dfs(new_x, new_y, path, visited) path.pop() visited.remove((new_x, new_y)) visited = set([start]) dfs(start[0], start[1], [start], visited) if all_paths: shortest_path = min(all_paths, key=len) print("最短路径:", shortest_path) else: print("未找到路径") ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值