POJ 2251 簡單BFS

這題雖然題目大,但是其實只是一道BFS最短路徑的裸題。

BFS之所以能求最短路是因爲它採用廣度優先搜索,每次接觸到的面時間都是相等的。所以在找的目的地時一定是最短路徑。

代碼如下

//
//  main.cpp
//  Code
//
//  Created by KFM on 16/6/25.
//  Copyright © 2016年 KFM. All rights reserved.
//

#include <iostream>
#include <cstdio>
#include <queue>
using namespace std;

#define maxn 45
int L,R,C;
char map[maxn][maxn][maxn];
int dis[6][3]= {{1,0,0},{-1,0,0},{0,1,0},{0,-1,0},{0,0,1},{0,0,-1}};

struct node{
    int x,y,z;
    int time;
    friend bool operator <(node n1,node n2)
    {
        return n1.time>n2.time;
    }
};

node b;
node e;

void BFS(){
    queue<node> q;
    q.push(b);
    map[b.x][b.y][b.z]='#';
    while(!q.empty()){
        node start = q.front();
        q.pop();
        if(start.x==e.x&&start.y==e.y&&start.z==e.z){
            printf("Escaped in %d minute(s).\n",start.time);
            return ;
        }
        for(int i=0;i<6;i++){
            node move;
            move.x=start.x+dis[i][0];
            move.y=start.y+dis[i][1];
            move.z=start.z+dis[i][2];
            if(move.x>=0&&move.x<L&&move.y>=0&&move.y<R&&move.z>=0&&move.z<C&&map[move.x][move.y][move.z]!='#'){
                move.time=start.time+1;
                map[move.x][move.y][move.z]='#';
                q.push(move);
            }
        }
    }
    printf("Trapped!\n");
}


int main() {
    while(~scanf("%d %d %d",&L,&R,&C)){
        if(!L&&!R&&!C) return 0;
        for(int i=0;i<L;i++)
            for(int j=0;j<R;j++)
                for(int k=0;k<C;k++){
                    cin>>map[i][j][k];
                    if(map[i][j][k]=='S'){b.x=i;b.y=j;b.z=k;}
                    if(map[i][j][k]=='E'){e.x=i;e.y=j;e.z=k;}
                }
        BFS();
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章