后来一看当时代码有点问题,vis里应该是total不是dist。。。这个题数据也太水了。。。已修正
——————————————————————————————————————
首先这题就是个水题,主要试验一下A*算法。
A*的思路:
f(g) = d(g) + h(g)
f(g)是预估长度,d(g)是走到当前点所用的距离,h(g)是从当前点走到目标点的预估距离,在二维方格地图中一般取曼哈顿距离作为预估。
算法核心流程:
1.每走一格更新当前点周围各点的f(g),并存入数组中;
2.每次取f(g)最小的点,并重复上步
这样路径搜索就有一定的趋向性,可以减小搜索量。
本题代码:
#include <bits/stdc++.h>
using namespace std;
struct Node{
int x, y, dist, total;
Node(){}
Node(int a, int b, int c, int d):x(a), y(b), dist(c), total(d){}
bool operator < (const Node &i) const{
return total > i.total;
}
};
priority_queue<Node> pq;
int vis[205][205];
char mp[205][205];
int d[4][2] = {1, 0, 0, 1, -1, 0, 0, -1};
int w, h;
int astar(int sx, int sy, int ex, int ey){
while(!pq.empty()) pq.pop();
Node node(sx, sy, 0, abs(ex - sx) + abs(ey - sy));
pq.push(node);
while(!pq.empty()){
node = pq.top();
pq.pop();
if(node.total >= vis[node.x][node.y]) continue;
else vis[node.x][node.y] = node.total;
for(int i = 0; i < 4; i++){
Node tmp(node.x + d[i][0], node.y + d[i][1], node.dist + 1, 0);
if(tmp.x >= w || tmp.y >= h || tmp.x < 0 || tmp.y < 0 || mp[tmp.x][tmp.y] == '#') continue;
if(mp[tmp.x][tmp.y] == 'x') tmp.dist++;
tmp.total = tmp.dist + abs(ex - tmp.x) + abs(ey - tmp.y);
if(tmp.total>= vis[tmp.x][tmp.y]) continue;
if(tmp.x == ex && tmp.y == ey) return tmp.dist;
pq.push(tmp);
}
}
return -1;
}
main() {
int sx, sy, ex, ey;
while(~scanf("%d %d", &w, &h)){
for(int i = 0; i < w; i++) {
scanf("%s", mp[i]);
for(int j = 0; j < h; j++){
if(mp[i][j] == 'r') sx = i, sy = j;
else if(mp[i][j] == 'a') ex = i, ey = j;
}
}
for(int i = 0; i < w; i++)
for(int j = 0; j < h; j++)
vis[i][j] = 1 << 30;
int res = astar(sx, sy, ex, ey);
if(res == -1) puts("Poor ANGEL has to stay in the prison all his life.");
else cout << res << endl;
}
}