hdu 1242 利用优先队列进行广搜

这题题目不难,代码也不长,花了一个小时,主要是之前没用过结构体的构造函数,比较函数与优先队列

/*
* hdu1242/linux.cpp
* Created on: 2011-9-4
* Author : ben
*/
#include
<cstdio>
#include
<cstdlib>
#include
<cstring>
#include
<cmath>
#include
<algorithm>
#include
<queue>
using namespace std;

typedef
struct Node {
int x, y;
int time;
Node(
int xx, int yy, int tt) {
x
= xx;
y
= yy;
time
= tt;
}
friend
bool operator<(const Node &n1, const Node &n2) {
return n1.time > n2.time;
}
} Node;

const int MAXN = 205;
const int move[4][2] = { { 1, 0 }, { 0, 1 }, { -1, 0 }, { 0, -1 } };
char map[MAXN][MAXN];
bool visited[MAXN][MAXN];
int M, N;

int work() {
int sx, sy, xx, yy;
priority_queue
<Node> pq;
memset(map,
'#', sizeof(map));
memset(visited,
false, sizeof(visited));
for (int i = 1; i <= M; i++) {
getchar();
for (int j = 1; j <= N; j++) {
map[i][j]
= getchar();
if (map[i][j] == 'a') {
sx
= i;
sy
= j;
}
}
}
pq.push(Node(sx, sy,
0));
visited[sx][sy]
= true;
while (!pq.empty()) {
Node cur
= pq.top();
pq.pop();
for (int i = 0; i < 4; i++) {
xx
= cur.x + move[i][0];
yy
= cur.y + move[i][1];
if (visited[xx][yy]) {
continue;
}
if (map[xx][yy] == '.') {
pq.push(Node(xx, yy, cur.time
+ 1));
}
else if (map[xx][yy] == 'x') {
pq.push(Node(xx, yy, cur.time
+ 2));
}
else if (map[xx][yy] == 'r') {
return cur.time + 1;
}
visited[xx][yy]
= true;
}
}
return -1;
}

int main() {
#ifndef ONLINE_JUDGE
freopen(
"data.in", "r", stdin);
#endif
int ans;
while (scanf("%d%d", &M, &N) == 2) {
ans
= work();
if (ans == -1) {
puts(
"Poor ANGEL has to stay in the prison all his life.");
}
else {
printf(
"%d\n", ans);
}
}
return 0;
}
posted @ 2011-09-04 22:39  moonbay  阅读(158)  评论(0编辑  收藏  举报