您的位置:首页 > 其它

ZOJ1649/HDU1242简单的BFS加上一点小的变形

2012-03-06 20:15 246 查看
此题的大致意思是在一个迷宫内,营救天使,r代表天使的朋友a代表天使,x代表卫兵;

见到卫兵就打死他这要多花1各单位时间,问你要多长时间才能到达天使所处的位置。

一见到此题第一反应就光搜代码很快就写完了,测试样例通过,直接提交我傻眼了,

WA一直WA纠结死了!我不信邪就去搜别人代码,第一眼看到的是优先队列。

我恍然大悟,我用的是普通队列只能一步步往外搜不能停顿,这是普通队列的优点也是缺点。

结果我使用优先队列后只是在我代码的基础上稍作改动即实现了优先队列的功能,

因为优先队列是按顺序从小到大排列时间的,所以用稍作修改果断0ms通过,真是开心啊!

#include<cstdio>
#include<cstring>
#include<iostream>
#include<limits.h>
#include<cstdlib>
#include<queue>

using namespace std;

typedef struct
{
int x, y;
int step;
}Point;

priority_queue<Point> q;
bool operator<(Point a, Point b)
{
return a.step > b.step;
}

char map[201][201];
int visit[201][201];
int N, M, ok, num, si, sj;
int dx[4] = {1,-1,0,0};
int dy[4] = {0,0,1,-1};

int True(Point V)
{
if(V.x>=0 && V.x<N && V.y>=0 && V.y<M)
return 1;
return 0;
}

int main()
{
int i, j, ax, ay;
Point Start, end;

while(scanf("%d%d", &N, &M) != EOF)
{
getchar();
for(i=0; i<N; i++)
{
scanf("%s",map[i]);
getchar();
}
for(i=0; i<N; i++)
for(j=0; j<M; j++)
{
if(map[i][j] == 'r')
{
si = i;
sj = j;
}
if(map[i][j] == 'a')
{
ax = i;
ay = j;
}
}
memset(visit, 0, sizeof(visit));
Start.x = si;
Start.y = sj;
Start.step = 0;
ok = 0;
visit[Start.x][Start.y] = 1;
q.push(Start);
while( !q.empty() )
{
Point u = q.top();
q.pop();
if(u.x==ax&&u.y==ay)
{
ok = 1;
printf("%d\n",u.step);
break;
}
for(i=0; i<4; i++)
{
Point v;
v.x = u.x + dx[i];
v.y = u.y + dy[i];
if(True(v)&&!visit[v.x][v.y]&&map[v.x][v.y]!='#')
{
if(map[v.x][v.y]=='x')
v.step = u.step + 2;
else
v.step = u.step + 1;
visit[v.x][v.y] = 1;
q.push(v);
}
}
}
if(!ok)
printf("Poor ANGEL has to stay in the prison all his life.\n");
while( !q.empty() )
{
q.pop();
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: