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

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

    不过题意还是要简单说下,'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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值