POJ3984(bfs+输出路径)

思路:题目要求输出每一次走的点,所以我的想法是给每个结点再加个id和fro代表他现在是第几个遍历的和他的根节点是谁,接下来就是常规的bfs了,把答案压到栈里面,最后输出。

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<string>
#include<vector>
#include<stack>
#include<bitset>
#include<cstdlib>
#include<cmath>
#include<set>
#include<list>
#include<deque>
#include<map>
#include<queue>
using namespace std;
#define inf 0x3f3f3f3f
#define ll long long
const int maxn=200005;
const double eps=1e-8;
const double PI = acos(-1.0);
int maz[6][6],vis[6][6];
struct node
{
    int x,y,step,fro,id;
    node (int x,int y,int s,int f,int i):x(x),y(y),step(s),fro(f),id(i){}
    node (){}
};
int dx[]={0,0,1,-1};
int dy[]={1,-1,0,0};
void bfs()
{
    node a(0,0,0,-1,0),all[1000];
    int tot=0;
    stack<node> ans;
    queue <node> q;
    all[0]=a;
    q.push(a);
    while(!q.empty())
    {
        node t=q.front();
        if(t.x==4&&t.y==4)
        {
            while(t.fro>=0)
            {
                ans.push(t);
                t=all[t.fro];
            }
            ans.push(a);
            while(!ans.empty())
            {
                node te=ans.top();
                printf("(%d, %d)\n",te.x,te.y);
                ans.pop();
            }
            break;
        }
        q.pop();
        for(int i=0;i<4;i++)
        {
            int tx=dx[i]+t.x;
            int ty=dy[i]+t.y;
            if(tx>=0&&tx<5&&ty>=0&&ty<5&&!vis[tx][ty]&&maz[tx][ty]==0)
            {
                ++tot;
                all[tot]= * new node(tx,ty,t.step+1,t.id,tot);
                q.push(all[tot]);
                vis[tx][ty]=1;
            }
        }
    }
}
int main()
{
    std::ios::sync_with_stdio(false);
    std::cin.tie(0);
    std::cout.tie(0);
    for(int i=0;i<5;i++)
    {
        for(int j=0;j<5;j++)
        {
            cin>>maz[i][j];
        }
    }
    bfs();
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Dilly__dally/article/details/81545867