HDU 1026 Ignatius and the Princess I BFS优先队列

来源:互联网 发布:游戏王灵兽使淘宝 编辑:程序博客网 时间:2024/05/16 11:12

    一看题目的输入输出这题的意思基本也就明白了......迷宫问题,肯定又要写麻烦的遍历了= =

    不过题意还是要简单说下,'X'是墙,'.'是路,迷宫的标准╮(╯_╰)╭起点是左上角,终点是右下角,数字是在这一点上要多费的时间,问最短时间走到终点的方法。一开始用dfs写没写出来= =好吧,写的乱乱的最后也没保留,最后又上网看了下改的bfs才搜出来最短路,然后再输出路径......好像也没什么可多说的了= =放代码吧......

#include<iostream>#include<cstdio>#include<cstring>#include<algorithm>#include<queue>using namespace std;char s[105];int mg[105][105];int vis[105][105];int hp[105][105];int change[4][2]={1,0,-1,0,0,1,0,-1};int n,m,tim;struct node{    int x,y,step;    friend bool operator<(node n1,node n2)    {        return n2.step<n1.step;    }};int bfs(){    int i;    node a,b;    priority_queue<node> q;    a.x=0;    a.y=0;    a.step=0;    mg[0][0]=-1;    q.push(a);    while(!q.empty())    {        a=q.top();        q.pop();        if(a.x==n-1&&a.y==m-1)            return a.step;        for(i=0;i<4;i++)        {            b=a;            b.x=b.x+change[i][0];            b.y=b.y+change[i][1];            if(b.x<0||b.y<0||b.x>=n||b.y>=m)                continue;            if(mg[b.x][b.y]==-1)                continue;            b.step=a.step+mg[b.x][b.y]+1;            mg[b.x][b.y]=-1;            vis[b.x][b.y]=i+1;            q.push(b);        }    }    return 0;}int print(int x,int y){    int tx,ty;    if(!vis[x][y])        return 0;    tx=x-change[vis[x][y]-1][0];    ty=y-change[vis[x][y]-1][1];    print(tx,ty);    cout<<tim<<"s:("<<tx<<","<<ty<<")->("<<x<<","<<y<<")"<<endl;    tim++;    while(hp[x][y]--)    {        cout<<tim<<"s:FIGHT AT ("<<x<<","<<y<<")"<<endl;        tim++;    }    return 0;}int main(){    int i,j;    int ans;    while(scanf("%d%d",&n,&m)!=EOF)    {        memset(mg,0,sizeof(mg));        memset(vis,0,sizeof(vis));        memset(hp,0,sizeof(hp));        memset(s,0,sizeof(s));        for(i=0;i<n;i++)        {            scanf("%s",s);            for(j=0;s[j];j++)            {                if(s[j]=='.')                {                    mg[i][j]=0;                }                else if(s[j]=='X')                {                    mg[i][j]=-1;                }                else                {                    mg[i][j]=s[j]-'0';                    hp[i][j]=s[j]-'0';                }            }        }        ans=0;        ans=bfs();        if(ans==0)        {            cout<<"God please help our poor hero."<<endl;        }        else        {            cout<<"It takes "<<ans<<" seconds to reach the target position, let me show you the way."<<endl;            tim=1;            print(n-1,m-1);        }        cout<<"FINISH"<<endl;    }    return 0;}


0 0
原创粉丝点击