hdu 1026 优先队列 + 路径保存

#include <iostream>
#include <queue>
#include<cstdio>
using namespace std;
#define maxsize 105
char map[maxsize][maxsize];
bool hash[maxsize][maxsize];
int n,m;
struct node
{
    int x,y;
    int time;
    int fro;
    int cost;
 
};
bool operator <(node a,node b)
{
 return a.time > b.time;
}
node N,P,p[10010],path[10010];
priority_queue<node>q;
int dir[4][2]={{1,0},{-1,0},{0,-1},{0,1}};
bool arrive;
int k;
void bfs ()
{
    while (!q.empty())
    q.pop();
    N.x = 0;
    N.y = 0;
    N.time = 0;
    N.fro = -1;
    N.cost = 0;
    k = 0;
    q.push (N);
    hash[0][0] = true;
    while (!q.empty())
    {
        N = q.top (); q.pop ();
        path[k] = N;
        if (N.x == n-1 && N.y == m-1)
        {
          
            arrive = true;
            return ;
        }
        for (int i = 0; i < 4; i++)
        {
            P.x = N.x + dir[i][0];
            P.y = N.y + dir[i][1];
   P.time = N.time + 1;
            if (P.x >= 0 && P.x < n && P.y >= 0 && P.y < m && map[P.x][P.y] != 'X' &&hash[P.x][P.y] == true)
            {
               
                if (map[P.x][P.y] > '0' && map[P.x][P.y] <= '9')
                {
                    P.time += map[P.x][P.y] -'0';
                    P.cost = map[P.x][P.y] -'0';
                }
                else P.cost = 0;
                P.fro = k;
                q.push (P);
                hash[P.x][P.y] = false;
            }
        }
        k++;
    }
   
}
void show()
 {
  int i,j,t,b=1,c=0;
  for(i = k; i >= 0; i = path[i].fro)
  {
   p[c++] = path[i];
  }
  if(arrive)
  {
   cout<<"It takes "<<N.time<<" seconds to reach the target position, let me show you the way."<<endl;
   for(i = c - 1;i >= 1; i--)
   {
    
    cout<<b++<<"s:("<<p[i].x<<","<<p[i].y<<")->("<<p[i-1].x<<","<<p[i-1].y<<")"<<endl;
      if(p[i - 1].cost != 0)
    {
       node t = p[i - 1];
     for(j = 0; j < t.cost; j++)
     {
     cout<<b++<<"s:FIGHT AT ("<<t.x<<","<<t.y<<")"<<endl;
     }
    }
  }
  
  }
  else
  {
  cout<<"God please help our poor hero."<<endl; 
  }
 }

int main ()
{
    while (cin>>n>>m)
    {
        int count = 0;
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < m; j++)
            {
                cin>>map[i][j];
                if(map[i][j] == 'X')
                count ++;
                hash[i][j] = true;
            }
        }
        if (n * m -count < (n+m-2))
        {
            cout<<"God please help our poor hero."<<endl;
   cout<<"FINISH"<<endl;
            continue;
        }
        arrive = false;
        bfs();
        show();
        cout<<"FINISH"<<endl;
    }
    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值