joj 2534

优先队列

 

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


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

class cmp
{
    public:
        bool operator ()(const Node & a, const Node & b)
        {
            return a.steps>b.steps; 
        }   
};   

priority_queue<Node,vector<Node>,cmp> q; 
char g[16][31];
int vir[16][31];
int di[16][31];
int dir[4][2] = {{0,1},{0,-1},{1,0},{-1,0}};

int main()
{
 int n, i, j;
 int sx, sy, ex, ey;
 cin >> n;
 while ( n-- )
 {
  while( !q.empty() )
  {
   q.pop();
  }
  for(i = 0; i < 15; i++)
  {
   for(j = 0; j < 30; j++)
   {
    cin >> g[i][j];
    vir[i][j] = 0;
    di[i][j] = 0;
    if( g[i][j] == 'S')
    {
     sx = j;
     sy = i;
    }
    if( g[i][j] == 'T')
    {
     ex = j;
     ey = i;
    }
   }
  }
  Node cur, star, temp;
  star.x = sx;
  star.y = sy;
  star.steps = 0;
  q.push(star);
  vir[sx][sy] = 1;
  while( !q.empty() )
  {
   cur = q.top();
   q.pop();
   for(i = 0; i < 4; i++)
   {
    temp.x = cur.x + dir[i][0];
    temp.y = cur.y + dir[i][1];
    if(g[temp.y][temp.x] != '#' && vir[temp.y][temp.x] == 0 && temp.x >= 0 && temp.y >= 0 && temp.x < 30 && temp.y < 15)
    {
     if(g[temp.y][temp.x] == '.' || g[temp.y][temp.x] == 'T')
     {
         temp.steps = cur.steps + 1;
         di[temp.y][temp.x] = cur.steps + 1;
     }
     if( g[temp.y][temp.x] == 'M' )
     {
      temp.steps = cur.steps + 2;
      di[temp.y][temp.x] = cur.steps + 2;
     }
     q.push(temp);
     vir[temp.y][temp.x] = 1;
    }
   }
  }
/*  for(i = 0; i < 15; i++)
  {
   for(j = 0; j < 30; j++)
   {
    cout << vir[i][j] << " ";
   }
   cout << endl;
  }
  cout << endl; 
     for(i = 0; i < 15; i++)
  {
   for(j = 0; j < 30; j++)
   {
    cout << di[i][j] << " ";
   }
   cout << endl;
  }
  cout << endl;   */
  if(vir[ey][ex] == 1)
  {
   cout << di[ey][ex]<< endl;
  }
  else
  {
   cout << "-1" << endl;
  }
 }
 return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值