书山有径勤为路>>>>>>>>

<<<<<<<<学海无涯苦作舟!

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");
    }
}

posted on 2012-04-28 16:51  More study needed.  阅读(713)  评论(0编辑  收藏  举报

导航

书山有径勤为路>>>>>>>>

<<<<<<<<学海无涯苦作舟!