这道题相比于平常的bfs走迷宫,多了一个,原来因为要维护步数优先的队列,所以先出队的元素永远处在步数+1的位置
但这个题由于杀死守卫需要多花一个步数,所以平常的队列不能做到按照这个,所以要使用到优先队列的技巧
优先队列结构体的使用方法:
struct node
{
int x;
int y;
int step;
node(int a,int b,int c)
{
x = a;
y = b;
step = c;
}
node(){}//面向对象的空构造方法
//优先队列怎么使用??????? 维护时间 让时间最早的先出来
bool operator < (const node &a) const { //重载的小于运算符 在push/top中用到了?
return step>a.step;//最小值优先
}
//que.push 根据优先级的适当位置 插入新元素
}s,t,temp;
priority_queue <node> que//STL
其中重载运算符的操作需要学习,这个的意思就是按照step的值,最小值优先
题目链接(openjudge和POJ今天维护,找时间再补)
#include <iostream>
#include <algorithm>
#include <queue>
#include <cstring>
#define maxn 205
#define INF 99999
using namespace std;
//WA点在于 应当以时间作为拓充
int m,n;
char map[maxn][maxn];
int vis[maxn][maxn];
int l[maxn][maxn];
struct node
{
int x;
int y;
int step;
node(int a,int b,int c)
{
x = a;
y = b;
step = c;
}
node(){}//面向对象的空构造方法
//优先队列怎么使用??????? 维护时间 让时间最早的先出来
bool operator < (const node &a) const { //重载的小于运算符 在push/top中用到了?
return step>a.step;//最小值优先
}
//que.push 根据优先级的适当位置 插入新元素
}s,t,temp;
int dx[4] = {1,0,-1,0};
int dy[4] = {0,1,0,-1};
void bfs()
{
priority_queue <node> que;//这个题要使用有线队列 保证时间先出来
que.push(s);
while(que.size())//每次会先走到时间优先 因此时间必须被放在结构体里
{
temp = que.top();//头上的永远是最小的时间
que.pop();
if(temp.x==t.x&&temp.y==t.y)
{
printf("%d\n",temp.step);
return ;
}
for(int i=0;i<4;i++)
{
int tx = temp.x+dx[i];
int ty = temp.y+dy[i];
if(tx>=0&&tx<m&&ty>=0&&ty<n&&map[tx][ty]!='#'&&vis[tx][ty]==0)//还没有被访问过
{
if(map[tx][ty]=='x') que.push(node(tx,ty,temp.step+2));
else que.push(node(tx,ty,temp.step+1)); //这步push隐含了什么?
vis[tx][ty] = 1;
}
}
}
printf("Impossible\n");
}
int main(void)
{
int g;
scanf("%d",&g);
while(g--)
{
memset(vis,0,sizeof(vis));
scanf("%d%d",&m,&n);
for(int i=0;i<m;i++)
{
scanf("%s",map[i]);
}
// printf("\n-----------------------------------------------------------------\n");
// for(int i=0;i<m;i++)
// {
// printf("%s\n",map[i]);
// }
// printf("\n-----------------------------------------------------------------\n");
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
if(map[i][j]=='x')//如果这个地方有守卫 则移动这一步所需要的花的时间2
{
l[i][j] = 2;
}
else
{
l[i][j] = 1;
}
if(map[i][j]=='r') s = node(i,j,0);
if(map[i][j]=='a') t = node(i,j,0);
}
}
bfs();
}
}
/*
K#OOO
O#O#O
O#r#O
O###O
OOOOO
*/