poj 3984 bfs+路径还原

来源:互联网 发布:前端ajax获取json数据 编辑:程序博客网 时间:2024/06/05 16:58

分析:路径还原相当于在搜索的过程中保留一个关系链,在这里搜索到最后一步后,输出第一步到最后一步经过的节点,最先考虑的是栈的存储
分析:代码主要分为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;}
原创粉丝点击