BFS最短路径的记录

在网上看到了一个记录BFS最短路径的方法,

个人觉得相当的牛B,所以就将它记录下来了。

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

这个题目比较简单,就不说题意了。

 

直接上代码:

View Code
#include "iostream"
#include "cstring"
#include "cstdio"
#include "algorithm"
#include "queue"
using namespace std;
#define MAX 1000000
typedef struct Path{
    int time;
    int x, y;
    int ttime;
}Path;
typedef struct Point{
    int x, y;
}Point;
int d[4][2]={{-1, 0}, {1, 0},{0, -1},{0, 1}};
Point p1, p2;
int Row, Col;
Path Map[105][105];//这个你想到用过吗,没有吧,就只是这个已经是很大的亮点了,也可以说是整个题目的最大亮点了
void BFS(){
    queue<Point> q;
    Map[0][0].time = 0;
    p1.x = Row-1;
    p1.y = Col-1;
    Map[Row-1][Col-1].ttime = Map[Row-1][Col-1].time;
    q.push(p1);
    while(!q.empty()){
        p1 = q.front();
        q.pop();
        if(p1.x==0 && p1.y==0) continue;
        for(int k=0; k<4; k++){
            p2.x = p1.x+d[k][0];
            p2.y = p1.y+d[k][1];
            if(p2.x<0 || p2.x>Row-1 || p2.y<0 || p2.y>Col-1 || Map[p2.x][p2.y].time==-1)
                continue;
            if(Map[p1.x][p1.y].ttime+Map[p2.x][p2.y].time<Map[p2.x][p2.y].ttime){
                Map[p2.x][p2.y].ttime = Map[p1.x][p1.y].ttime+Map[p2.x][p2.y].time;
                Map[p2.x][p2.y].x = p1.x;
                Map[p2.x][p2.y].y = p1.y;
                q.push(p2);
            }
        }
    }
}
int main(){
    char ch;
    while(cin>>Row>>Col){
        getchar();
        for(int i=0; i<Row; i++){
            for(int j=0; j<Col; j++){
                cin>>ch;
                Map[i][j].ttime = MAX;
                if(ch=='.') Map[i][j].time = 1;
                else if(ch=='X') Map[i][j].time = -1;
                else Map[i][j].time = ch-'0'+1;
            }
            getchar();
        }
        int i, j, k, h;
        BFS();
        if(Map[0][0].ttime==MAX) printf("God please help our poor hero.\n");
        else{
            i=0;j=k=0;
            printf("It takes %d seconds to reach the target position, let me show you the way.\n",Map[0][0].ttime);
            while(i<Map[0][0].ttime){
                if(Map[j][k].time>1){
                    while(--Map[j][k].time){
                        i++;
                        printf("%ds:FIGHT AT (%d,%d)\n",i,j,k);

                    }
                }else{
                    i++;
                    printf("%ds:(%d,%d)->(%d,%d)\n",i,j,k,Map[j][k].x,Map[j][k].y);
                    h=Map[j][k].x;
                    k=Map[j][k].y;
                    j=h;
                }
            }
        }
        printf("FINISH\n");
    }
}

转载于:https://www.cnblogs.com/o8le/archive/2012/04/28/2475418.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值