题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1026
题目大意:求用时最短路线并打印路径,n表示用n秒打败怪兽。
题目分析:bfs+优先队列求出最短用时,path数组记录路径,栈输出路径。
代码参考:
#include <queue>
#include <stack>
#include <cstdio>
#include <vector>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 109;
priority_queue<int> pq;//优先队列
struct Node
{
int x, y, step;
friend bool operator < (const Node &a, const Node &b) { //定义排序规则
return a.step > b.step;
}
}p[N][N],path[N][N];
char edge[N][N];//保存地图
bool vis[N][N];
int dir[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
int n, m, minStep;
int bfs(Node s)
{
priority_queue<Node> Q;
Q.push(s);
vis[0][0] = 1;
while(!Q.empty()) {
Node head = Q.top();
Q.pop();
if(head.x == n - 1 && head.y == m - 1) { //如果走到了终点,返回最短用时
return head.step;
}
for(int i = 0; i < 4; ++ i) { //枚举4个方向
int x = head.x + dir[i][0];
int y = head.y + dir[i][1];
if(x >= 0 && x < n && y >= 0 && y < m && edge[x][y] != 'X' && !vis[x][y]) { //判定是否可走
vis[x][y] = 1;
path[x][y].x = head.x; //保存路径
path[x][y].y = head.y;
path[x][y].step = head.step + 1;
Node t; //当前点
t.x = x;
t.y = y;
t.step = head.step + 1;
if(edge[x][y] == '.') {
Q.push(t);
} else {
t.step = t.step + edge[x][y] - '0'; //加上打怪兽的时间
Q.push(t);
}
}
}
}
return -1; //如果没有走到终点
}
void print()
{
if(minStep == -1) { //如果没有走到终点
puts("God please help our poor hero.");
} else { //输出最短用时
printf("It takes %d seconds to reach the target position, let me show you the way.\n", minStep);
stack<Node> st; //栈输出
Node t = path[n - 1][m - 1];
Node rmin;
rmin.x = n - 1;
rmin.y = m - 1;
rmin.step = minStep;
st.push(rmin);
while(t.x || t.y) { //如果到了终点
st.push(t); //将路径压入栈内
t = path[t.x][t.y];
}
int k = 1;
while(!st.empty()) {
t = st.top();
st.pop();
printf("%ds:(%d,%d)->(%d,%d)\n", k ++, path[t.x][t.y].x, path[t.x][t.y].y, t.x, t.y);
if(edge[t.x][t.y] != '.') {
int fight = edge[t.x][t.y] - '0';
while(fight --) {
printf("%ds:FIGHT AT (%d,%d)\n", k ++, t.x, t.y);
}
}
}
}
puts("FINISH");
return;
}
int main()
{
while(~scanf("%d%d", &n, &m)) {
memset(vis, 0, sizeof(vis));
for(int i = 0; i < n; ++ i) {
scanf("%s", edge[i]);
}
Node start; //起点
start.x = start.y = start.step = 0;
minStep = bfs(start);
print(); //打印路径
}
return 0;
}