POJ 3984 - 迷宫问题 - [BFS水题]

题目链接:http://poj.org/problem?id=3984

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)

 

题解:

裸的BFS水题。

 

AC代码:

#include<cstdio>
#include<cstring>
#include<queue>
#include<stack>
using namespace std;
const int dx[4]={0,1,0,-1};
const int dy[4]={1,0,-1,0};

int mp[5][5];
struct Node{
    int x,y;
    int cnt;
    Node(){}
    Node(int _x,int _y,int _cnt) {
        x=_x, y=_y, cnt=_cnt;
    }
    inline bool out() {
        return x<0 || x>=5 || y<0 || y>=5;
    }
};
queue<Node> Q;
bool vis[5][5];
Node pre[5][5];
stack<Node> ans;

int main()
{
    memset(mp,1,sizeof(mp));
    for(int i=0;i<5;i++) for(int j=0;j<5;j++) scanf("%d",&mp[i][j]);

    memset(vis,0,sizeof(vis));
    Q.push((Node){0,0,0});
    vis[0][0]=1;
    while(!Q.empty())
    {
        Node now=Q.front(); Q.pop();
        if(now.x==4 && now.y==4)
        {
            ans.push(now);
            break;
        }
        for(int k=0;k<4;k++)
        {
            Node nxt=Node(now.x+dx[k],now.y+dy[k],now.cnt+1);
            if(nxt.out()) continue;
            if(mp[nxt.x][nxt.y]) continue;
            if(vis[nxt.x][nxt.y]) continue;
            Q.push(nxt);
            vis[nxt.x][nxt.y]=1;
            pre[nxt.x][nxt.y]=now;
        }
    }

    while(ans.top().cnt) ans.push(pre[ans.top().x][ans.top().y]);
    while(!ans.empty())
    {
        printf("(%d, %d)\n",ans.top().x,ans.top().y);
        ans.pop();
    }
}

 

posted @ 2018-10-31 15:40  Dilthey  阅读(428)  评论(0编辑  收藏  举报