迷宫问题

简介: bfs

定义一个二维数组:

int maze5 = {

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表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。
Input
一个5 × 5的二维数组,表示一个迷宫。数据保证有唯一解。
Output
左上角到右下角的最短路径,格式如样例所示。
Sample
Input
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
Output
(0, 0)
(1, 0)
(2, 0)
(2, 1)
(2, 2)
(2, 3)
(2, 4)
(3, 4)
(4, 4)

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<queue>
#define M 5
#define N 5

using namespace std;

int maze[M][N],vis[M][N];
int dx[4]={0,1,0,-1};
int dy[4]={1,0,-1,0};
struct point{
    int x;
    int y;
}pr[10][10];
queue<point> q;
void bfs(){
    point s;
    s.x=0,s.y=0;
    q.push(s);
    vis[0][0]=1;
    while(!q.empty()){
        point p=q.front();
        q.pop();
        if(p.x==M-1&&p.y==N-1){
            return;
        }
        for(int i=0;i<4;i++){
            int a,b;
            a=p.x+dx[i];
            b=p.y+dy[i];
            if(!maze[a][b]&&!vis[a][b]&&a>=0&&a<5&&b>=0&&b<5){
                point t;
                t.x=a;
                t.y=b;
                q.push(t);
                vis[a][b]=1;
                pr[a][b]=p;
            }
        }
    }
}
void output(point p){
    if(!p.x&&!p.y){
        cout<<"(0, 0)"<<endl;
        return;
    }
    output(pr[p.x][p.y]);
    cout<<"("<<p.x<<", "<<p.y<<")"<<endl;
}

int main(){
    for(int i=0;i<5;i++){
        for(int j=0;j<5;j++){
            scanf("%d",&maze[i][j]);
        }
    }
    bfs();
    point end;
    end.x=4;
    end.y=4;
    output(end);
} 
相关文章
|
2天前
|
存储 算法
使用 BFS 解决走迷宫问题
使用 BFS 解决走迷宫问题
43 1
|
2天前
|
算法 Java C++
走迷宫(BFS)
走迷宫(BFS)
28 0
|
10月前
1252:走迷宫 2021-01-05
1252:走迷宫 2021-01-05
|
10月前
1255:迷宫问题 2021-01-09
1255:迷宫问题 2021-01-09
|
10月前
|
机器学习/深度学习
1215:迷宫
1215:迷宫
AcWing——方格迷宫(有点不一样的迷宫问题)
AcWing——方格迷宫(有点不一样的迷宫问题)
55 0
|
定位技术 C++
基于c++深度优先遍历迷宫
基于c++深度优先遍历迷宫
108 0
基于c++深度优先遍历迷宫
迷宫最短路径问题
迷宫最短路径问题
211 0
迷宫最短路径问题
|
定位技术 C++
C++ 迷宫问题
C++ 迷宫问题
200 0
|
存储 定位技术 C++
【31. 走迷宫(BFS)】
## 思路 - 用 `g[n][m] `存储地图,`d[n][m]` 存储起点到 n,m 的距离。 - 从起点开始广度优先遍历地图。 - 当地图遍历完,就求出了起点到各个点的距离,输出`d[n][m]`即可。
243 0
【31. 走迷宫(BFS)】