HDU 1026 Ignatius and the Princess I

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");
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值