NYOJ--284--广搜+优先队列--坦克大战

/*
    Name: NYOJ--284--坦克大战
    Author: shen_渊 
    Date: 14/04/17 19:08
    Description: 广度优先搜索+优先队列
                注意清空地图 
                对输入地图进行了预处理,将S,R设置为# 
*/

#include<iostream> 
#include<queue> 
#include<cstring>
using namespace std;
const char YOU = 'Y';
const char TARGET = 'T';
const char RIVER = 'R' ;
const char SWALL = 'S';
const char BWALL = 'B';
const char EMPOTY = 'E';
const char FORBID = '#';
struct node{
    int x,y,steps;
    node():steps(0){};
    bool operator <(const node &a)const{
        return steps>a.steps;    
    }
}you,target;
int bfs();
int check(char);
char map[305][305] = {0};
int m,n;
int dir[4][2] = {{0,1},{0,-1},{1,0},{-1,0}};
int main()
{
//    ios::sync_with_stdio(false);
//    freopen("in.txt","r",stdin);

    while(cin>>m>>n, m || n) {
        int i,j;
        memset(map,0,sizeof(map));
        for(i=1; i<=m; ++i){
            for(j=1; j<=n; ++j){
                cin>>map[i][j];
                switch(map[i][j]){
                    case YOU:{
                        you.x = i;you.y = j;
                        break;
                    }
                    case TARGET:{
                        target.x = i;target.y = j;
                        break;
                    }
                    case RIVER: 
                    case SWALL:{
                        map[i][j] =='#';
                        break;
                    }    
                    default:break;
                }
            }
        }
        cout<<bfs()<<endl;
    }
    return 0;
}
int bfs(){
    priority_queue<node> Q;
    while(!Q.empty())Q.pop();
    Q.push(you);
    map[you.x][you.y] = '#';
    while(!Q.empty()){
        node p = Q.top();Q.pop();
        int i,j;
        for(i=0; i<4; ++i){
            node a;
            a.x = p.x + dir[i][0];
            a.y = p.y + dir[i][1];
            if(a.x<1|| a.y<1|| a.x>m|| a.y>n)continue;
            int next;
            if(next = check(map[a.x][a.y])){
                a.steps = p.steps + next;
                if(a.x == target.x && a.y == target.y)return a.steps;
                Q.push(a);
                map[a.x][a.y] = '#';
            }
        }
    }
    return -1;
}
int check(char ch){
    switch(ch){
        case TARGET:return 1;
        case EMPOTY:return 1; 
        case BWALL:return 2;
    }
    return 0;
}

 

posted @ 2017-04-14 21:25  朤尧  阅读(237)  评论(0编辑  收藏  举报