POJ3984迷宫问题(BFS+路径记录)

先附上题目链接:

http://poj.org/problem?id=3984

这道水题主要是看BFS的路径如何记录,除此之外就是一个裸裸的BFS, 在此不再解释BFS。
关于路径记录有好多方法(好多大佬的方法看不太懂哎),我比较喜欢用string记录(DFS也是),相比于其他方法,用string简单好写而且容易理解,下边简单介绍一下。
DFS和BFS中用string记录路径,stringstream就表现得十分强大了,可以手动拼字符串。

附上AC代码,并在注释简要说明:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <cmath>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <iterator>
#include <sstream> //stringstream所需的头文件
#define rep(i,a,b) for(int i=(a);i<=(b);i++)
#define per(i,a,b) for(int i=(a);i>=(b);i--)
#define ms(s,x) memset(s,x,sizeof(s))
#define pb push_back
#define inf 0x3f3f3f3f
typedef long long ll;
using namespace std;

const int MAXN = 1e5+5;
const int MOD = 1e9+7;

struct node
{
    int x, y, step;
    string road; //记录BFS路径
} a, b;

int pic[9][9];
bool vis[9][9];
char dir[4][2] = {-1,0, 0,-1, 0,1, 1,0};

int main()
{
    queue <node> que;
    ms(vis, 0);
    rep(i, 0, 4)
        rep(j, 0, 4)
            cin >> pic[i][j];
    a.x = a.y = a.step = 0;
    a.road = "(0, 0)\n"; //加\n输出时自动换行
    que.push(a);
    vis[0][0] = 1;
    while (!que.empty())
    {
        a = que.front();
        que.pop();
        if (a.x == 4 && a.y == 4)
            break;
        rep(i, 0, 3)
        {
            int x = a.x + dir[i][0];
            int y = a.y + dir[i][1];
            if (x>=0 && y>=0 && x<=4 && y<=4 && !pic[x][y] && !vis[x][y])
            {
                vis[x][y] = 1;
                stringstream st;
                st << "(" << x << ", " << y << ")\n";
                b.x = x, b.y = y, b.step = a.step+1;
                b.road = a.road + st.str();
                //注意此处不要写b.road += st.str(),这样会记录搜索到的每一个点
                que.push(b);
            }
        }
    }
    cout << a.road << endl;
    
    return 0;
}

欢迎大佬们指出错误和不足。


版权声明:本文为weixin_45609737原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。