HDU 1242 Rescue (BFS + 优先队列)

青旅半醒 2024-02-17 18:56 153阅读 0赞
  1. #include<cstdio>
  2. #include<queue>
  3. #include<cstring>
  4. using namespace std;
  5. const int maxn=200+10;
  6. char p[maxn][maxn]; //保存字符
  7. int d[maxn][maxn]; //从开始位置到当前位置花的时间长度
  8. struct node{
  9. int x,y;
  10. node(int x1=0,int y1=0):x(x1),y(y1){}
  11. bool operator<(const node & n)const{
  12. return d[x][y]>d[n.x][n.y];
  13. }
  14. };
  15. node a;
  16. node r;
  17. int N,M;
  18. const int dir[][2]={
  19. {-1,0},{1,0},{0,-1},{0,1}};
  20. bool isValid(const node &v){
  21. return v.x>=0 && v.x<N && v.y>=0 && v.y<M;
  22. }
  23. void bfs(){
  24. priority_queue<node>q; //优先队列,整数值越小越先出队列
  25. q.push(r);
  26. memset(d,0,sizeof(d));
  27. while(!q.empty()){
  28. node u=q.top();q.pop();
  29. if(u.x== a.x && u.y== a.y){ //如果找到 Angel 就 输出所花时间 并退出 BFS
  30. printf("%d\n",d[u.x][u.y]);
  31. return ;
  32. }
  33. for(int i=0;i<4;i++){
  34. node v=node(u.x+dir[i][0],u.y+dir[i][1]);
  35. if(isValid(v)&& !d[v.x][v.y] && p[v.x][v.y]!='#'){
  36. if(p[v.x][v.y]=='x')d[v.x][v.y]=d[u.x][u.y]+2;
  37. else d[v.x][v.y]=d[u.x][u.y]+1;
  38. q.push(v);
  39. }
  40. }
  41. }
  42. printf ("Poor ANGEL has to stay in the prison all his life.\n");
  43. }
  44. int main(){
  45. while(scanf("%d%d",&N,&M)==2){
  46. memset(p,0,sizeof(p));
  47. for(int i=0;i<N;i++)scanf("%s",p[i]);
  48. for(int i=0;i<N;i++){
  49. for(int j=0;j<M;j++){
  50. if(p[i][j]=='a'){
  51. a.x=i;a.y=j;
  52. }
  53. else if(p[i][j]=='r'){
  54. r.x=i;r.y=j;
  55. }
  56. }
  57. }
  58. bfs();
  59. }
  60. return 0;
  61. }

发表评论

表情:
评论列表 (有 0 条评论,153人围观)

还没有评论,来说两句吧...

相关阅读

    相关 HDU 1242(bfs)

    题意:一个朋友拯救angel,'a' 是angel, 'x'是士兵, 'r'是朋友,'\'是墙壁。没走一步花费一个单位的时间,遇到士兵与士兵搏斗花费一个单位的时间,求最短时间。