您的位置:首页 > 产品设计 > UI/UE

HDOJ 1242 BFS+priority_queue

2018-01-25 13:06 441 查看
题目:http://acm.hdu.edu.cn/showproblem.php?pid=1242

#include<bits/stdc++.h>
#define PI 3.1415926
#define INF 1e18
#define inf 1e9
#define min(a,b) a<b?a:b
#define max(a,b) a>b?a:b
using namespace std ;
typedef long long ll;
typedef unsigned long long ull;

const int _max = 205;
struct node{
int x,y,cnt;
void init(int x,int y,int cnt){
this->x=x;
this->y=y;
this->cnt=cnt;
}
bool operator < (const node &n1)const{
return cnt > n1.cnt;
}
};
char mp[_max][_max];
bool vis[_max][_max];
int dx[]={0,0,1,-1};
int dy[]={1,-1,0,0};
int n,m;
bool outside(node n1){
if(n1.x < 1 || n1.x > m) return true;
if(n1.y < 1 || n1.y > n) return true;
return false;
}
int dfs(int sx,int sy,int ex,int ey){
node now,next;
priority_queue<node> q;
while(!q.empty()) q.pop();
now.init(sx,sy,0);
q.push(now);
vis[sy][sx]=false;
while(!q.empty()){
now = q.top();
q.pop();
if(now.x == ex && now.y == ey)
return now.cnt;
for(int i = 0 ; i < 4 ; i++){
next.init(now.x+dx[i],now.y+dy[i],now.cnt+1);
if(!outside(next)&&vis[next.y][next.x]&&mp[next.y][next.x]!='#'){
if(mp[next.y][next.x]=='x')
next.cnt++;
vis[next.y][next.x] = false;
q.push(next);
}
}
}
return -1;
}
int main(){
int sx,sy,ex,ey;
while(cin>>n>>m){
memset(vis,true,sizeof(vis));
for(int y = 1 ; y <= n ; y++)
for(int x = 1 ;  x <= m ; x++){
cin >> mp[y][x];
if(mp[y][x]=='r'){
sx = x;
sy = y;
}
if(mp[y][x]=='a'){
ex = x;
ey = y;
}
}
int ans =dfs(sx,sy,ex,ey);
if(ans == -1) cout<<"Poor ANGEL has to stay in the prison all his life."<<endl;
else cout<<ans<<endl;
}
return 0 ;
}


终于摆脱了,见到迷宫就dfs的场景了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  HDOJ bfs 优先队列