您的位置:首页 > 其它

HDU 1026 Ignatius and the Princess I

2015-08-15 18:05 302 查看
HDU 1026 Ignatius and the Princess I

http://acm.hdu.edu.cn/showproblem.php?pid=1026

依然是BFS的题目,这次不同的是需要把路径进行记录。计算最短路径的值跟裸题一样,就不重复了,主要的不同是用pre数组把每个点的前一个元素记录下来,最后用迭代的方式把路径输出。

#include<cstdio>
#include<queue>
#include<cstring>
#define INF 10000000
using namespace std;

char maze[120][120];
int dx[4] = {1, 0, -1, 0}, dy[4] = {0, 1, 0, -1};
int dis[120][120];
typedef pair<int, int> P;
int n, m;
P pre[120][120];
void bfs(){
queue<P> que;
que.push(P(0, 0));
dis[0][0] = 0;
while(!que.empty()){
P p = que.front();
que.pop();
//if(p.first == n - 1 && p.second == m - 1) break;
for(int i = 0;i < 4;i++){
int nx = p.first + dx[i], ny = p.second + dy[i];
if(nx >= 0 && nx < n && ny >= 0 && ny < m && maze[nx][ny] != 'X'){
if(maze[nx][ny] == '.'){
if(dis[p.first][p.second] + 1 < dis[nx][ny]){
dis[nx][ny] = dis[p.first][p.second] + 1;
pre[nx][ny].first = p.first;
pre[nx][ny].second = p.second;
que.push(P(nx, ny));
}
}
else{
if(dis[p.first][p.second] + (maze[nx][ny] - '0') + 1 < dis[nx][ny]){
dis[nx][ny] = dis[p.first][p.second] + (maze[nx][ny] - '0') + 1;
pre[nx][ny].first = p.first;
pre[nx][ny].second = p.second;
que.push(P(nx, ny));
}
}
}
}
}
}

void print_pre(int i, int j){
if(pre[i][j].first == -1) return ;
print_pre(pre[i][j].first, pre[i][j].second);
if(maze[i][j] == '.')
printf("%ds:(%d,%d)->(%d,%d)\n",dis[i][j],pre[i][j].first, pre[i][j].second,i, j);
else{
int num = maze[i][j] - '0';
int t = dis[i][j] - num;
printf("%ds:(%d,%d)->(%d,%d)\n",t++, pre[i][j].first, pre[i][j].second, i, j);
for(int k = 1;k <= num;k++){
printf("%ds:FIGHT AT (%d,%d)\n",t++, i, j);        }
}
}
main(){
while(~scanf("%d %d", &n, &m)){
getchar();
for(int i = 0;i < n;i++){
gets(maze[i]);
}
for(int i = 0;i < n;i++){
for(int j = 0;j < m;j++){
dis[i][j] = INF;
}
}
pre[0][0].first = pre[0][0].second = -1;
bfs();
if(dis[n-1][m-1] == INF)
printf("God please help our poor hero.\n");
else{
printf("It takes %d seconds to reach the target position, let me show you the way.\n",dis[n-1][m-1]);
print_pre(n-1,m-1);
}

puts("FINISH");
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: