這道題相比於平常的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
*/