POJ 迷宫问题(经典BFS问题)

Description

定义一个二维数组:

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表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。

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

Sample Output

(0, 0)
(1, 0)
(2, 0)
(2, 1)
(2, 2)
(2, 3)
(2, 4)
(3, 4)
(4, 4)

Source

Time Limit: 1000MS Memory Limit: 65536K

思路:用BFS遍历,用pre数组记录不同子节点的父节点,vis数组记录是否已访问,Qiang数组记录墙的位置。
代码如下:

#include <iostream>
#include <queue>
#include <cstring>
using namespace std;
struct node{
    int x;
    int y;
}; 
node pre[5][5];
int Qiang[5][5];
bool vis[5][5];
int CorX[] = {0,1,0,-1};
int CorY[] = {1,0,-1,0};
void print(node lr){
    if(lr.x==0&&lr.y==0)
        cout<<"(0,0)"<<endl;
    else{
        print(pre[lr.x][lr.y]);
        cout<<"("<<lr.x<<","<<lr.y<<")"<<endl;
    }
}
void bfs(int x1,int y1){   
    queue<node> q;
    q.push(node{x1,y1});
    vis[x1][y1] = true;
    while(!q.empty()){
        node tmp = q.front();
        q.pop();
        for(int i=0;i<4;i++){
            int xx = tmp.x+CorX[i];
            int yy = tmp.y+CorY[i];
            if(xx<0||xx>4||yy<0||yy>4||Qiang[xx][yy]||vis[xx][yy]) continue;
            node lr = node{xx,yy};
            q.push(lr);
            pre[xx][yy] = tmp;
            vis[xx][yy] = true;
            if(xx==4&&yy==4){
                print(lr);
                return; 
            }
        }
    }
}
int main(){
    memset(Qiang,0,sizeof(Qiang));
    memset(vis,false,sizeof(vis));
    for(int i=0;i<5;i++)
        for(int j=0;j<5;j++)
            cin>>Qiang[i][j];
    bfs(0,0);
    return 0;
} 

输出结果如下:

(0,0)
(1,0)
(2,0)
(2,1)
(2,2)
(2,3)
(2,4)
(3,4)
(4,4)
    原文作者:迷宫问题
    原文地址: https://blog.csdn.net/SL_World/article/details/79677847
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞