经典迷宫问题BFS

给定一个迷宫,入口为左上角,出口为右下角,问是否有路径从入口到出口,若有则输出一条这样的路径。注意移动可以从上、下、左、右、上左、上右、下左、下右八个方向进行。迷宫输入0表示可走,输入1表示墙。易得可以用1将迷宫围起来避免边界问题。

本题采用BFS算法给出解。注意,利用BFS算法给出的路径必然是一条最短路径。

/*
迷宫问题(八方向)
input:
1
6 8
0 1 1 1 0 1 1 1
1 0 1 0 1 0 1 0
0 1 0 0 1 1 1 1
0 1 1 1 0 0 1 1
1 0 0 1 1 0 0 0
0 1 1 0 0 1 1 0
output:
YES
(1,1) (2,2) (3,3) (3,4) (4,5) (4,6) (5,7) (6,8)
*/
#include<iostream>
#include<queue>
#include<stack>
using namespace std;
struct point{
    //横坐标纵坐标
    int x;
    int y;
};
int **Maze;     //初始化迷宫
point **Pre;    //保存任意点在路径中的前一步
point move[8]={{-1,-1},{-1,0},{-1,1},{0,-1},{0,1},{1,-1},{1,0},{1,1}};      //移动方向,横竖斜都可以,八个方向
void Create(int row,int column){
    //创建迷宫,注意到用0表示可走,1表示墙,将整个输入的迷宫再用墙围着,处理的时候就不用特别注意边界问题
    int i,j;
    for(i=0; i<row+2; i++)
		Maze[i][0] = Maze[i][column+1] = 1;
    for(j=0; j<column+2; j++)
		Maze[0][j] = Maze[row+1][j] = 1;
    for(i=1; i<=row; i++){
        for(j=1; j<=column; j++){
            cin>>Maze[i][j];
        }
    }
}
bool MazePath(int row,int column,int x,int y){
    //判断是否有路径从入口到出口,保存该路径(队列)
    if(x == row && y == column)return true;
    queue<point> q;     //用于广度优先搜索
    point now;          //当前位置
    now.x = x;
    now.y = y;
    q.push(now);
    Maze[now.x][now.y] = -1;
    while(!q.empty()){
        now = q.front();
        q.pop();
        for(int i=0; i<8; i++){
            if(now.x + move[i].x == row && now.y + move[i].y == column){
                Maze[now.x + move[i].x][now.y + move[i].y] = -1;
                Pre[row][column] = now;
                return true;
            }
            if(Maze[now.x + move[i].x][now.y + move[i].y] == 0){
                point temp;     //下个位置
                temp.x = now.x + move[i].x;
                temp.y = now.y + move[i].y;
                q.push(temp);
                Maze[temp.x][temp.y] = -1;
                Pre[temp.x][temp.y] = now;

            }
        }
    }
    return false;
}
void PrintPath(int row,int column){
    //输出最短路径
    point temp;         //保存位置
    stack<point> s;     //保存路径序列
    temp.x = row;
    temp.y = column;
    while(temp.x != 1 || temp.y != 1){
        s.push(temp);
        temp = Pre[temp.x][temp.y];
    }
    cout<<"(1,1)";
    while(!s.empty()){
        temp = s.top();
        cout<<' '<<'('<<temp.x<<','<<temp.y<<')';
        s.pop();
    }
    cout<<endl;
}
int main(){
    int t;          //用例数量
    int row;        //迷宫行数
    int column;     //迷宫列数
    cin>>t;
    while(t--){
        cin>>row>>column;
        Maze = new int*[row + 2];
        Pre = new point*[row + 2];
        for(int i=0; i<row+2; i++){
            Maze[i] = new int[column + 2];
            Pre[i] = new point[column + 2];
        }
        Create(row,column);
		if(MazePath(row,column,1,1)){
		    cout<<"YES"<<endl;
		    PrintPath(row,column);
		}
		else cout<<"NO"<<endl;
    }
    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("未找到路径") ```
评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值