杭电1242Rescue题(bfs+优先队列)

举报
Linux猿 发表于 2021/08/05 22:24:05 2021/08/05
【摘要】 杭电1242Rescue题(bfs+优先队列) 题目链接~~> 这题是学习优先队列的第一题搞了好久才AC: 先介绍一下优先队列: 头文件: #include<queue> using namespace std; 由大到小出队: struct zhang { int x,y; friend bool operator<(cons...

杭电1242Rescue题(bfs+优先队列)

题目链接~~>

这题是学习优先队列的第一题搞了好久才AC:奋斗

先介绍一下优先队列:

头文件:


  
  1. #include<queue>
  2. using namespace std;

由大到小出队:


  
  1. struct zhang
  2. {
  3. int x,y;
  4. friend bool operator<(const zhang &a,const zhang &b)
  5. {
  6. return a.x < b.x ;
  7. }
  8. };
  9. priority_queue<zhang>q;
  10. zhang current;

由小到大出队:
           将上面的 return a .x < b.x ;中的 "<" 改为 “>” ;但传说中这种方法G++编译器编译不过;

(非本人)代码:

 

   
  1. #include <iostream>
  2. #include <stdio.h>
  3. #include <string.h>
  4. #include <queue>
  5. #define N 201
  6. using namespace std;
  7. //优先队列解决,广度优先
  8. struct Persion
  9. {
  10. int x,y;
  11. int time;
  12. friend bool operator < (const Persion &a,const Persion &b)
  13. {
  14. return a.time>b.time; //">" 返回队列中较小的元素;"< " 则返回队列中较大的元素
  15. }
  16. };
  17. int dir[4][2]={{-1,0},{1,0},{0,-1},{0,1}};
  18. char map[N][N];
  19. int visited[N][N];
  20. int m,n;
  21. int BFS(int x,int y)
  22. {
  23. priority_queue <Persion>q;
  24. Persion current,next;
  25. memset(visited,0,sizeof(visited));
  26. current.x=x;
  27. current.y=y;
  28. current.time=0;
  29. visited[current.x][current.y]=1;
  30. q.push(current);
  31. while(!q.empty())
  32. {
  33. current=q.top();
  34. q.pop();
  35. for(int i=0;i<4;i++)
  36. {
  37. next.x=current.x+dir[i][0];
  38. next.y=current.y+dir[i][1];
  39. if(next.x>=0&&next.x<n&&next.y>=0&&next.y<m&&map[next.x][next.y]!='#'&&!visited[next.x][next.y])
  40. {
  41. if(map[next.x][next.y]=='r')
  42. return current.time+1;
  43. if(map[next.x][next.y]=='x')
  44. next.time=current.time+2;
  45. else
  46. next.time=current.time+1;
  47. visited[next.x][next.y]=1;
  48. q.push(next);
  49. }
  50. }
  51. }
  52. return -1;
  53. }
  54. int main()
  55. {
  56. int i,j;
  57. Persion angle;
  58. while(cin>>n>>m&&(m||n))
  59. {
  60. for(i=0;i<n;i++)
  61. for(j=0;j<m;j++)
  62. {
  63. cin>>map[i][j];
  64. if(map[i][j]=='a')
  65. {
  66. angle.x=i;
  67. angle.y=j;
  68. }
  69. }
  70. int time=BFS(angle.x,angle.y);
  71. if(time==-1)
  72. cout<<"Poor ANGEL has to stay in the prison all his life."<<endl;
  73. else
  74. cout<<time<<endl;
  75. }
  76. return 0;
  77. }


 





 

文章来源: blog.csdn.net,作者:Linux猿,版权归原作者所有,如需转载,请联系作者。

原文链接:blog.csdn.net/nyist_zxp/article/details/9154235

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。