您的位置:首页 > 产品设计 > UI/UE

hdu 1242 Rescue BFS+优先队列

2016-04-06 14:04 253 查看
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1242

题意:"r"是起点,"a"是终点,'.'是路,'x'是守卫,'#'是不能走的地方。杀掉守卫要多花1个单位时间,每次上下左右移动要花一个单位时间。问到终点花的最少时间。

思路:这种N*M的地图且带权(一个是1,一个是2)的一般使用BFS+优先队列,如果不带权可以直接使用BFS。

#include <bits/stdc++.h>
using namespace std;
int N, M;
#define maxn 210
#define inf 0x3f3f3f3f
char mp[maxn][maxn];
int sx, sy, ex, ey;
int dir[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
struct Node
{
int x, y, d;
Node(int xx, int yy, int dd)
{
x = xx; y = yy; d = dd;
}
Node(){}
friend bool operator <(Node a, Node b)
{
return a.d > b.d;
}
};
int dist[maxn][maxn];
int bfs()
{
memset(dist, inf, sizeof(dist));
priority_queue <Node> q;
dist[sx][sy] = 0;
q.push(Node(sx, sy, 0));
while(!q.empty())
{
Node u = q.top(); q.pop();
for(int i = 0; i < 4; i++)
{
int xx = u.x + dir[i][0];
int yy = u.y + dir[i][1];
//cout<<xx<<" "<<yy<<endl;
if(xx < 0 || xx >= N || yy < 0 || yy >= M || mp[xx][yy] == '#') continue;
if(mp[xx][yy] == 'a') return u.d+1;

Node temp = Node(xx, yy, u.d);
temp.d++;
if(mp[xx][yy] == 'x') temp.d++;
if(dist[xx][yy] >= temp.d)
{
q.push(temp);
dist[xx][yy] = temp.d;
}
}
}
return -1;

}
int main()
{
//freopen("in.txt", "r", stdin);
//freopen("out.txt", "w", stdout);
while(~scanf("%d%d", &N, &M))
{
for(int i = 0; i < N; i++)
{
scanf("%s", mp[i]);
}
for(int i = 0; i < N; i++)
{
for(int j = 0; j < M; j++)
{
if(mp[i][j] == 'r'){sx = i; sy = j;}
if(mp[i][j] == 'a'){ex = i; ey = j;}
}
}
int ans = bfs();
if(ans == -1) printf("Poor ANGEL has to stay in the prison all his life.\n");
else printf("%d\n", ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: