优先队列
#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;
}