您的位置:首页 > 其它

sdau-2 1012

2016-04-17 18:06 253 查看
问题:小a被抓了,小r我要去劫狱,看到狱警“x‘就干掉,问我能不能把小a救出来,能救就输出最短时间,我走一步和干掉一个狱警都要1单位时间。

etc:

7 8

#.#####.

#.a#..r.

#..#x...

..#..#.#

#...##..

.#......

........

simple out:13

r是我,a是小a,#是墙,x是狱警。

思路:我懵逼了,这就是bfs加优先队列啊

但为啥我老是超时?求高人请教。

代码:

#include<iostream>

#include<queue>

using namespace std;

int n,m;

char map[100][100];

int dir[4][2]={{1,0},{-1,0},{0,1},{0,-1}};

struct node{

    int x,y;

    int move;
friend bool operator<(node x1,node x2){
return x1.move>x2.move;
}

}p,c;

int bfs(int x,int y){
priority_queue<node>Q;

    p.x=x;

    p.y=y;

    p.move=0;

    Q.push(p);
int fx,fy;

    while(!Q.empty()){

        p=Q.top();

        Q.pop();

        for(int i=0;i<4;i++){

            fx=dir[i][0]+p.x;

            fy=dir[i][1]+p.y;

            if(fx>=0&&fx<n&&fy>=0&&fy<m&&map[fx][fy]!='#'){

                if(map[fx][fy]=='a'){

                    return p.move+1;

                }

                else if(map[fx][fy]=='.'){

                    c.move=p.move+1;

                }

                else if(map[fx][fy]=='x'){

                    c.move=p.move+2;

                }

                c.x=fx;

                c.y=fy;

                map[c.x][c.y]='#';

                Q.push(c);

            }

        }

    }

    return 0;

}

int main(){

    freopen("s.txt","r",stdin);

    while(cin>>n>>m&&n!=0&&m!=0){

        int x,y;

        for(int i=0;i<n;i++){

            for(int j=0;j<m;j++){

                cin>>map[i][j];

                if(map[i][j]=='r'){

                    x=i;

                    y=j;

                }

            }

        }

        int s=bfs(x,y);

        if(s)

            cout<<s<<endl;

        else

            cout<<"Poor ANGEL has to stay in the prison all his life."<<endl;

    }

    return 0; 

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: