HDU 1026 Ignatius and the Princess I(优先队列+BFS+打印路径)

#include<stdio.h>
#include<string.h>
#include<queue>
#include<algorithm>
using namespace std;
const int maxm=150;
int dir[4][2]={{1,0},{-1,0},{0,1},{0,-1}};
char s[maxm][maxm];
int map[maxm][maxm];
int vis[maxm][maxm];
int list[maxm][maxm];
int m,n;
int ok;
int cnt;
struct node
{
    int x,y,step;
    bool operator <(const node &s)const
    {
        return step>s.step;
    }
};
void print(int x,int y)
{
    int next_x,next_y;
    if(list[x][y]==0)
    {
       return;
    }
    next_x=x-dir[list[x][y]-1][0];
    next_y=y-dir[list[x][y]-1][1];
    print(next_x,next_y);
    printf("%ds:(%d,%d)->(%d,%d)\n",cnt++,next_x,next_y,x,y);
    while(vis[x][y]--)
    {
        printf("%ds:FIGHT AT (%d,%d)\n",cnt++,x,y);
    }
    return;
}
void bfs()
{
    struct node pre,now;
    priority_queue<node>q;
    pre.x=0;
    pre.y=0;
    pre.step=0;
    map[pre.x][pre.y]=-1;
    q.push(pre);
    while(!q.empty())
    {
        pre=q.top();
        q.pop();
        if(pre.x==m-1&&pre.y==n-1)
        {
            ok=1;
            printf("It takes %d seconds to reach the target position, let me show you the way.\n",pre.step);
            return;
        }
        for(int i=0;i<4;i++)
        {
            now.x=pre.x+dir[i][0];
            now.y=pre.y+dir[i][1];
            if(now.x>=0&now.x<m&&now.y>=0&&now.y<n&&map[now.x][now.y]!=-1)
            {

                now.step=pre.step+map[now.x][now.y]+1;
                list[now.x][now.y]=i+1;
                map[now.x][now.y]=-1;
                q.push(now);
            }
        }
    }
    return;
}
int main()
{
    while(scanf("%d%d",&m,&n)!=EOF)
    {
        int i,j;
        ok=0;
        memset(vis,0,sizeof(vis));
        for(i=0;i<m;i++)
        {
            scanf("%s",s[i]);
            for(j=0;j<n;j++)
            {
                if(s[i][j]=='.')
                {
                    map[i][j]=0;
                }
                if('1'<=s[i][j]&&s[i][j]<='9')
                {
                    vis[i][j]=map[i][j]=s[i][j]-'0';
                }
                if(s[i][j]=='X')
                {
                    map[i][j]=-1;
                }
            }
        }
        cnt=1;
        bfs();
        if(ok)
        {
          print(m-1,n-1);
        }
        else
        {
             printf("God please help our poor hero.\n");
        }
        printf("FINISH\n");
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值