http://acm.hdu.edu.cn/showproblem.php?pid=1026
题意:给出一个迷宫,求出到终点的最短时间路径。
这道题目在迷宫上有怪物,不同HP的怪物会损耗不同的时间,这个时候可以用优先队列,每次让时间最短的出队列。由于最后还需要输出路径,所以需要设置一个数组来保存路径。
#include<iostream>
#include<queue>
#include<cstring>
using namespace std; const int maxn = + ; struct node
{
int x, y;
int time;
friend bool operator < ( node a, node b) //重载<号
{
return b.time<a.time;
}
}; char map[maxn][maxn];
int visited[maxn][maxn];
int path[maxn][maxn];
int n, m;
int d[][] = { { , }, { -, }, { , }, { , - } }; int bfs()
{
node q,now;
priority_queue<node> p;
q.x = ;
q.y = ;
q.time = ;
p.push(q);
while (!p.empty())
{
q = p.top();
p.pop();
if (q.x == n - && q.y == m - ) return q.time;
for (int i = ; i < ; i++)
{
int xx = q.x + d[i][];
int yy = q.y + d[i][];
now.x = xx;
now.y = yy;
now.time = q.time;
if (xx >= && xx < n && yy >= && yy < m && map[xx][yy]!='X' && !visited[xx][yy])
{
if (map[xx][yy] == '.') now.time++;
else now.time =now.time+ (map[xx][yy] - ''+);
visited[xx][yy] = ;
path[xx][yy] = i + ; //记录路径
p.push(now);
}
}
}
return -;
} int temp; void print(int x, int y)
{
int xx, yy;
if (path[x][y] == ) return;
xx = x - d[path[x][y] - ][]; //寻找第一个路径点
yy = y - d[path[x][y] - ][];
print(xx, yy);
printf("%ds:(%d,%d)->(%d,%d)\n", temp++, xx, yy, x, y);
if (map[x][y] <= '' && map[x][y] >= '')
{
int m = map[x][y] - '';
while (m--) printf("%ds:FIGHT AT (%d,%d)\n", temp++, x, y);
}
} int main()
{
while (cin >> n >> m && (n||m))
{
memset(visited, , sizeof(visited));
memset(path, , sizeof(path));
for (int i = ; i < n;i++)
for (int j = ; j < m; j++)
cin >> map[i][j];
visited[][] = ;
int ans=bfs();
if (ans == -) cout << "God please help our poor hero." << endl;
else
{
cout << "It takes " << ans << " seconds to reach the target position, let me show you the way." << endl;
temp = ;
print(n - ,m - );
}
cout << "FINISH" << endl;
}
return ;
}