POJ - 3984 -迷宫问题【BFS + 打印路径】

题解:  用一个结构体二维数组来存每个点的上一个点的坐标,通过递归到达起点,在回溯时打印路径

#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
int mp[5][5];
bool vis[5][5];
int dir[4][2] = {0, 1, 0, -1, 1, 0, -1, 0};
struct node
{
    int x, y;
}Step[5][5];;
void bfs()
{
    memset(vis, 0, sizeof(vis));
    node S, E;
    S.x = 0, S.y = 0;
    E.x = 4, E.y = 4;
    queue<node> q;
    q.push(S);
    while(!q.empty())
    {
        node now = q.front();
        if(now.x == E.x && now.y == E.y)
        {
            return;
        }
        q.pop();
        node next;
        for(int i = 0; i < 4; i++)
        {
            next.x = now.x + dir[i][0];
            next.y = now.y + dir[i][1];
            if(next.x < 5 && next.x >= 0 && next.y < 5 && next.y >= 0 && !vis[next.x][next.y] && mp[next.x][next.y] != 1)
            {
                Step[next.x][next.y].x = now.x;
                Step[next.x][next.y].y = now.y;
                 vis[next.x][next.y] = true;
                q.push(next);
            }
        }
    }
}
void print(int x, int y)
{
    if(x == 0 && y == 0)
    {
        printf("(0, 0)\n");
        return;
    }
    print(Step[x][y].x, Step[x][y].y);
    printf("(%d, %d)\n", x, y);
}
int main()
{
    memset(mp, 0, sizeof(mp));
    for (int i = 0; i < 5; i++)
        for (int j = 0; j < 5; j++)
            cin >> mp[i][j];
     bfs();
     print(4, 4);
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值