JOJ 2534 The Hero Rescued The Princess

从题要用到优先队列,里面加了一个排序的函数。第一次用到优先队列。

 

题目链接:http://acm.jlu.edu.cn/joj/showproblem.php?pid=2534

 

#include <iostream>
#include <queue>
#include <vector>
using namespace std;


char map[18][35];
int visited[18][35];
int dir[][2]={{0,1},{0,-1},{1,0},{-1,0}};

struct Point
{
 int x, y;
 int steps;
};

//定义cmp函数
class cmp
{
 public:
  bool operator()(const Point &a, const Point &b)
  {
   return a.steps > b.steps;
  }
};


int main()
{
 int T, i, j;
 int sx, sy, dx, dy, d, flag;
 cin>>T;
 while(T--)
 {
  for(i = 0; i < 15; i++)
  {
   for(j = 0; j < 30; j++)
   {
    //scanf("%c",&map[i][j]); //输入地图
    cin>>map[i][j];
    if(map[i][j]=='S')
    {
     sx = i;
     sy = j;
    }
    if(map[i][j]=='T')
    {
     dx = i;
     dy = j;
    }
   }
  }
  
  
  
  memset(visited,0,sizeof(visited));
  Point temp, cur, res;
  priority_queue<Point,vector<Point>,cmp> myqueue; //优先队列
 
   //清空栈的操纵
  while(!myqueue.empty())
  {
   myqueue.pop();
  }
  flag = 0;
  temp.x = sx;
  temp.y = sy;
  temp.steps = 0;
  res.steps = 0;
  visited[sx][sy] = 1; //开始的位置标志已经访问
  
  myqueue.push(temp);  //开始位置入栈
  
  while(!myqueue.empty())
  {
   cur = myqueue.top(); //zhe kuai yi ding yao zhu yi top().
   myqueue.pop();
   
   if(cur.x == dx&&cur.y == dy)
   {
    flag = 1;
    res.steps = cur.steps;
    break;
   }
   
   else
   {
    for(i = 0; i < 4; i++)
    {
     int X = cur.x + dir[i][0];
     int Y = cur.y + dir[i][1];
    
     if(map[X][Y]!='#'&&visited[X][Y]==0&&X>=0&&X<15&&Y>=0&&Y<30)
     {
      visited[X][Y] = 1;
      temp.x = X;
      temp.y = Y;
      
      
      if(map[temp.x][temp.y]=='M')
       temp.steps = cur.steps + 2;
      else
       temp.steps = cur.steps + 1;
      myqueue.push(temp);
     }
    }
   }
  }
  if(!flag)
   cout<<"-1"<<endl;
  else
   cout<<res.steps<<endl;
 }
 return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值