poj 3984 bfs+路径还原

本文介绍了一种基于宽度优先搜索(BFS)实现的路径寻回算法。通过详细讲解代码实现,展示了如何在二维网格中寻找从起点到终点的路径,并记录下路径上的每个节点。该算法适用于多种场景下的路径规划问题。

分析:路径还原相当于在搜索的过程中保留一个关系链,在这里搜索到最后一步后,输出第一步到最后一步经过的节点,最先考虑的是栈的存储
分析:代码主要分为2部分:宽搜和路径还原

#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <stack>
#include <queue>
#include <algorithm>
#include <cstring>
#include <string>
#include <cmath>
#include <vector>
#include <bitset>
#include <list>
#include <sstream>
#include <set>
#include <functional>
using namespace std;

typedef pair<int,int> p;
queue <p> qu;
p pre[5][5];
int d[5][5];
int map[5][5];
int x[4] = {-1,1,0,0};
int y[4] = {0,0,-1,1};

void bfs()
{
    while (!qu.empty()){
        p f = qu.front(); 
        qu.pop(); 
        int xi = f.first;
        int yi = f.second; 
        map[xi][yi] = 1;
        for (int i = 0; i < 4; i += 1){
            int nx = xi+x[i];
            int ny = yi+y[i];
            if (nx >= 0 && nx < 5 && ny >= 0 && ny < 5 && map[nx][ny] == 0){
                pre[nx][ny] = make_pair(xi,yi);
                qu.push(p(nx,ny));
            }
        }
    }
}

void find()
{
    stack<p> path;
    p point = make_pair(4,4);
    path.push(point);
    while (1){
        if(point.first == 0 && point.second == 0) break;
        point = pre[point.first][point.second];
        path.push(point);
    }
    while (!path.empty()){
        point = path.top();
        path.pop();
        cout << "(" << point.first << ", " << point.second << ")" << endl;
    }
}

int main(int argc, char const* argv[])
{
    for (int i = 0; i < 5; i += 1){
        for (int j = 0; j < 5; j += 1){
            cin >> map[i][j];
        }
    }
    qu.push(p(0,0));
    bfs();
    find();
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值