hdu1026(BFS,打印路径)

来源:互联网 发布:游戏最多的软件 编辑:程序博客网 时间:2024/06/06 07:11

题目链接:hdu1026

思路:用BFS搜,用数组dir[i][j]记录该点是由哪一个方向上的点遍历过来的,v[i][j]记录是否在该点上遇到怪物。BFS搜索完以后,再由终点向起点搜,同时打印路径

#include<cstdio>#include<cstring>#include<algorithm>#include<queue>#define MAXN 105using namespace std;char map[MAXN][MAXN];int dir[MAXN][MAXN];int v[MAXN][MAXN];const int d[4][2] = {{0,-1},{1,0},{0,1},{-1,0}};int n,m,flag,time;struct node{    int x,y;    int step;    friend bool operator < (node a,node b)    {        return a.step > b.step;    }};void print(int x,int y){    if(x == 0 && y == 0) return;    int next_x = x - d[dir[x][y]][0];    int next_y = y - d[dir[x][y]][1];    print(next_x,next_y);    printf("%ds:(%d,%d)->(%d,%d)\n",time++,next_x,next_y,x,y);    while(v[x][y] > 0)        printf("%ds:FIGHT AT (%d,%d)\n",time++,x,y),v[x][y]--;}void bfs(){    memset(dir,-1,sizeof(dir));    memset(v,-1,sizeof(v));    priority_queue <node> q;    node s,temp;    int endx = n - 1;    int endy = m - 1;    s.x = 0;    s.y = 0;    s.step = 0;    map[s.x][s.y] = 'X';    q.push(s);    while(!q.empty())    {        temp = q.top();        q.pop();        if(temp.x == endx && temp.y == endy)        {            flag = 1;            printf("It takes %d seconds to reach the target position, let me show you the way.\n",temp.step);            time = 1;            print(endx,endy);            return;        }        for(int i = 0; i < 4; i ++)        {            s = temp;            s.x += d[i][0];            s.y += d[i][1];            if(s.x < 0 || s.x >= n || s.y < 0 || s.y >= m || map[s.x][s.y] == 'X')            continue;            if(map[s.x][s.y] != '.')            {                s.step += map[s.x][s.y] - '0';                v[s.x][s.y] = map[s.x][s.y] - '0';            }            s.step ++;            dir[s.x][s.y] = i;//记录该点是由哪个方向的点遍历过来的            map[s.x][s.y] = 'X';            q.push(s);        }    }}int main(){    int i,j;    while(~scanf("%d%d",&n,&m))    {        for(i = 0; i < n; i ++)        scanf("%s",map[i]);        flag = 0;        bfs();        if(!flag) printf("God please help our poor hero.\n");        printf("FINISH\n");    }    return 0;}


原创粉丝点击