从题要用到优先队列,里面加了一个排序的函数。第一次用到优先队列。
题目链接: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;
}