HDU 1242 Rescue

怼烎@ 2022-04-16 04:59 262阅读 0赞

原题目链接HDU1242


分类

HDU 搜索 BFS 优先队列


题意

X代表卫兵,a代表终点,r代表起始点,.代表路,#代表墙

路花费一秒,x花费两秒

问到达终点的最少时间


样例输入输出

Sample Input

  1. 7 8
  2. #.#####.
  3. #.a#..r.
  4. #..#x...
  5. ..#..#.#
  6. #...##..
  7. .#......
  8. ........

Sample Output

  1. 13

想法

BFS+优先队列的裸题(第一次不看题解写出来的优先队列题,虽然是最基础的题目,赞)


代码

93ms

  1. #include<bits/stdc++.h>
  2. #define maxn 1111
  3. using namespace std;
  4. int n,m;
  5. int sx,sy;
  6. char Map[maxn][maxn];
  7. int vis[maxn][maxn];
  8. int dis[4][2] = { { -1,0},{ 0,-1},{ 0,1},{ 1,0}};
  9. struct node{
  10. int x,y,step;
  11. friend bool operator < (node a,node b){
  12. return b.step<a.step;
  13. }
  14. };
  15. bool check(int x,int y){
  16. if(x>=0&&x<n&&y>=0&&y<m&&!vis[x][y]&&Map[x][y]!='#') return true;
  17. return false;
  18. }
  19. int bfs(int x,int y){
  20. priority_queue <node> q;
  21. node s;
  22. s.x = x;
  23. s.y = y;
  24. s.step = 0;
  25. vis[x][y] =1;
  26. q.push(s);
  27. while(!q.empty()){
  28. node temp1 = q.top();
  29. q.pop();
  30. for(int i=0;i<4;i++){
  31. node temp2 = temp1;
  32. temp2.x+=dis[i][0];
  33. temp2.y+=dis[i][1];
  34. temp2.step+=1;
  35. if(check(temp2.x,temp2.y)){
  36. if(Map[temp2.x][temp2.y]=='a')
  37. return temp2.step;
  38. if(Map[temp2.x][temp2.y]=='x')
  39. temp2.step++;
  40. vis[temp2.x][temp2.y] = 1;
  41. q.push(temp2);
  42. }
  43. }
  44. }
  45. return 0;
  46. }
  47. int main()
  48. {
  49. while(scanf("%d%d",&n,&m)!=EOF){
  50. for(int i=0;i<n;i++){
  51. scanf("%s",Map[i]);
  52. for(int j =0;j<m;j++){
  53. if(Map[i][j]=='r'){
  54. sx = i;
  55. sy = j;
  56. }
  57. }
  58. }
  59. memset(vis,0,sizeof(vis));
  60. int ans = bfs(sx,sy);
  61. if(ans){
  62. printf("%d\n",ans);
  63. }else{
  64. printf("Poor ANGEL has to stay in the prison all his life.\n");
  65. }
  66. }
  67. return 0;
  68. }

发表评论

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

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

相关阅读

    相关 HDU 1242(bfs)

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