Ignatius and the Princess I HDU - 1026 (BFS-优先队列-输出路径)

#include <stdio.h>
#include <algorithm>
#include <functional>
#include <queue>
#include <cstring>

using namespace std;

int n, m;
int dir[4][2] = {0,1, 0,-1 , 1,0 , -1,0};

struct Node
{
    int time;
    int x, y;
    int prex, prey;    
    bool operator < (const Node & node) const
    {
        return time > node.time;    //按照time从小到大排序 
    }
} node[105][105];     //由于要回溯寻路,故要把路径记录到内存中,因此开辟数组来记录 

bool mark[105][105];
char map[105][105];   //保存地图 

int BFS()
{
    int i;
    int mx, my;
    Node cur;
    priority_queue<Node> pq;     //优先队列
    
    mark[0][0] = true;
    node[0][0].time = 0;
    pq.push(node[0][0]);

    while (!pq.empty())
    {
        cur = pq.top();
        pq.pop();

        if (cur.x == n - 1 && cur.y == m - 1)
            return cur.time;

        for (i = 0; i < 4; i++)
        {
            mx = cur.x + dir[i][0];
            my = cur.y + dir[i][1];
            
            if(mx <  0 || my < 0 || mx >= n || my >= m)
                continue;
            if(map[mx][my] == 'X')
                continue;
            if(mark[mx][my])
                continue;
            
            mark[mx][my] = true;
            node[mx][my].time = cur.time + 1;
            node[mx][my].prex = cur.x;
            node[mx][my].prey = cur.y;
            node[mx][my].x = mx;
            node[mx][my].y = my;
            if(map[mx][my] >= '1' && map[mx][my] <= '9')
                node[mx][my].time += map[mx][my] - '0';
            pq.push(node[mx][my]);
        }
    }
    return -1;
}

void printPath(int x, int y)
{
    if (x == 0 && y == 0)
        return;
    int prex = node[x][y].prex;
    int prey = node[x][y].prey;

    printPath(prex, prey);      //递归打印 
    
    int prelength = node[prex][prey].time;
    int length = node[x][y].time;
    printf("%ds:(%d,%d)->(%d,%d)\n", prelength + 1, prex, prey, x, y);
    for (int i = prelength + 2; i <= length; i++)
        printf("%ds:FIGHT AT (%d,%d)\n", i, x, y);
}

int main()
{
    int i, j;

    while (~scanf("%d%d", &n, &m))
    {
        for (i = 0; i < n; i++)
            scanf("%s", &map[i]);
        memset(mark, 0, sizeof(mark));    
        
        int ans = BFS();
        if (ans == -1)
        {
            printf("God please help our poor hero.\n");
            printf("FINISH\n");
            continue;
        }
        printf("It takes %d seconds to reach the target position, let me show you the way.\n", ans);
        printPath(n-1, m-1);
        printf("FINISH\n");
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/mch2869253130/article/details/82180485