题目链接:Click here~~
好累啊,写篇博客歇歇。
题目背景很有趣,是大家小时候经常玩的坦克大战,哈哈。弱弱地表示本人小时候经常玩游戏机。
此题是在迷宫问题的基础上做了些改动,就是地图上能走的点可能耗费时间1,也可能耗费时间2。
那么,元素在出队列时,不能简单的按照以前的入队顺序出队了,而应该让时间最短的先出队,
这样就能够保证先入队的点一定是时间最短的,那么搜到终点时也时间也一定最小。
现在回头想下,迷宫问题之所以没有考虑这个问题,是因为先入队的点的时间一定不大于后入队的。
言归正传,如何让时间最短的先出队呢?----------STL已经帮我们弄好了,priority_queue;
话说优先队列我也是新接触的,用法见代码吧,大家一起学习。
最近广搜做的不少,代码也比较清晰了吧。
#include <queue>
#include <stdio.h>
#include <string.h>
#define bug puts("here!!!")
using namespace std;
typedef struct p
{
int x,y,step;
}Ac;
struct cmp
{
bool operator ()(Ac s1,Ac s2)
{
return s1.step > s2.step;
}
};
priority_queue<Ac,vector<Ac>,cmp> S;
int dir[]={0,1,0,-1,1,0,-1,0};
int map[302][302];
int to_x,to_y;
int bfs()
{
while(!S.empty())
{
Ac R = S.top();
S.pop();
for(int k=0;k<8;)
{
int x = R.x + dir[k++];
int y = R.y + dir[k++];
if(x == to_x && y == to_y)
return R.step + 1;
if(map[x][y])
{
S.push({x,y,R.step + map[x][y]});
map[x][y]=0;
}
}
}
return -1;
}
void clear()
{
while(!S.empty())
S.pop();
}
int main()
{
int h,w;
while(scanf("%d%d",&h,&w),h||w)
{
getchar();
memset(map,0,sizeof(map));
for(int i=1;i<=h;i++)
{
for(int j=1;j<=w;j++)
{
char c = getchar();
switch(c)
{
case 'Y':S.push({i,j,0});break;
case 'T':to_x =i,to_y =j;break;
case 'B':map[i][j]=2;break;
case 'E':map[i][j]=1;break;
}
}
getchar();
}
printf("%d\n",bfs());
clear();
}
return 0;
}