POJ3984 输出路径

时间:2020-04-11
本文章向大家介绍POJ3984 输出路径,主要包括POJ3984 输出路径使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

    和ACWING 844基本一样。但是这里要输出路径    

    我的做法是,pair一个ing[x][y],ing[x][y].first,ing[x][y].second记录x,y的前一个点。因为是逆序,所以又存进一个结构体里,再逆序输出,才变成正序了。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
typedef pair<int,int>P; //!!!
const int maxn = 105;
P ing[maxn][maxn];
int n,m;
int g[maxn][maxn];
int d[maxn][maxn];    //每个点到起点的距离 //没有走过 
int dx[]={0,0,-1,1};
int dy[]={1,-1,0,0};
struct node
{
    int x,y;
}st[maxn];
void bfs()
{
    queue<P>q;
    memset(d,-1,sizeof(d));
    d[0][0]=0;
    q.push({0,0});
    while(!q.empty())
    {
        P t = q.front();
        q.pop();
        for(int i=0;i<4;i++)
        {
            int x=dx[i]+t.first;
            int y=dy[i]+t.second;
            if(x>=0&&y>=0&&x<5&&y<5&&g[x][y]==0&&d[x][y]==-1)
            {
                d[x][y]=d[t.first][t.second]+1;
                ing[x][y].first=t.first;
                ing[x][y].second=t.second;
                q.push({x,y});
            }
        }
    }
    return ;
}
int main()
{
    //cin>>n>>m;
    for(int i=0;i<5;i++)
        for(int j=0;j<5;j++)
            cin>>g[i][j];
    bfs();
    int x=4,y=4;
    int tot=0;
    while(!(x==0&&y==0))
    {
        st[tot].x=x;
        st[tot].y=y;
        tot++;
        int tx=x,ty=y;
        x=ing[tx][ty].first;
        y=ing[tx][ty].second;
    }
    cout<<"(0, 0)"<<endl;
    for(int i=tot-1;i>=0;i--)
        printf("(%d, %d)\n",st[i].x,st[i].y);
    return 0;
}

原文地址:https://www.cnblogs.com/liyexin/p/12680840.html