[kuangbin]专题一 简单搜索 迷宫问题 POJ - 3984【BFS】

【题目描述】
定义一个二维数组:
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)

题目链接:https://cn.vjudge.net/problem/POJ-3984

用t数组存下全部过程,用*pre还原路径

代码如下:

#include <iostream>
#include <queue>
#include <stack>
#include <cstring>
using namespace std;
static const int MAXN=5;
static const int dx[]={0,0,1,-1},dy[]={1,-1,0,0};
int mp[MAXN+2][MAXN+2];
bool vis[MAXN+2][MAXN+2];
struct Node{
    int x,y;
    int step;
    Node *pre;
};
void bfs(Node node)
{
    queue<Node> Q;
    Q.push(node);
    vis[node.x][node.y]=true;
    int cnt=-1;
    Node t[30];
    while(!Q.empty())
    {
        cnt++;
        t[cnt]=Q.front();
        Q.pop();
        for(int i=0;i<4;i++)
        {
            Node next;
            next.x=t[cnt].x+dx[i];
            next.y=t[cnt].y+dy[i];
            next.step=t[cnt].step+1;
            if(0<=next.x && next.x<5 && 0<=next.y && next.y<5 && mp[next.x][next.y]==0 && !vis[next.x][next.y])
            {
                vis[next.x][next.y]=true;
                next.pre=&t[cnt];
                if(next.x==4 && next.y==4)
                {
                    stack<Node> S;
                    while(next.pre)
                    {
                        S.push(next);
                        next=*(next.pre);
                    }
                    cout<<"(0, 0)"<<endl;
                    while(!S.empty())
                    {
                        Node temp=S.top();
                        S.pop();
                        cout<<"("<<temp.x<<", "<<temp.y<<")"<<endl;
                    }
                    return;
                }
                Q.push(next);
            }
        }
    }

}
int main()
{
    std::ios::sync_with_stdio(false);
    std::cin.tie(0),cout.tie(0);
    for(int i=0;i<5;i++)
        for(int j=0;j<5;j++)
            cin>>mp[i][j];
    memset(vis,false,sizeof(vis));
    bfs(Node{0,0,0,NULL});
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值