[关闭]
@lychee123 2017-03-18T13:09:03.000000Z 字数 1470 阅读 934

HDU-1072:Nightmare(BFS)

BFS


题面链接

  1. #include<stdio.h>
  2. #include<iostream>
  3. #include<queue>
  4. #include<string.h>
  5. #include<algorithm>
  6. using namespace std;
  7. int dir[4][2]={1,0,-1,0,0,1,0,-1};
  8. int vis[111][111];///vis[x][y]为起点到坐标为(x,y)的点的最短距离
  9. int i,j,x,y,t,n,m;
  10. int a[111][111];///输入的矩阵
  11. struct node
  12. {
  13. int x,y,step,time;
  14. };
  15. int BFS()
  16. {
  17. node now,next;
  18. queue<node>q;
  19. now.x=x;
  20. now.y=y;
  21. now.step=0;
  22. now.time=6;
  23. q.push(now);
  24. vis[now.x][now.y]=6;
  25. while(!q.empty())
  26. {
  27. now=q.front();
  28. q.pop();
  29. for(i=0;i<4;i++)
  30. {
  31. next.x=now.x+dir[i][0];
  32. next.y=now.y+dir[i][1];
  33. if(next.x>=0&&next.x<m&&next.y>=0&&next.y<n&&a[next.x][next.y]!=0)
  34. {
  35. next.step=now.step+1;
  36. next.time=now.time-1;
  37. if(next.time<=0)
  38. continue;
  39. if(a[next.x][next.y]==4)
  40. {
  41. a[next.x][next.y]=0;
  42. next.time=6;
  43. }
  44. if(a[next.x][next.y]==3)
  45. {
  46. if(next.time>0)
  47. {
  48. t=next.step;
  49. return t;
  50. }
  51. }
  52. if(next.time>=1&&vis[next.x][next.y]<next.time)
  53. {
  54. vis[next.x][next.y]=next.time;
  55. q.push(next);
  56. }
  57. }
  58. }
  59. }
  60. return -1;
  61. }
  62. int main()
  63. {
  64. int k,count;
  65. scanf("%d",&k);
  66. while(k--)
  67. {
  68. memset(vis,0,sizeof(vis));
  69. memset(a,0,sizeof(a));
  70. scanf("%d%d",&m,&n);
  71. for(i=0;i<m;i++)
  72. {
  73. for(j=0;j<n;j++)
  74. scanf("%d",&a[i][j]);
  75. }
  76. for(i=0;i<m;i++)
  77. for(j=0;j<n;j++)
  78. {
  79. if(a[i][j]==2)
  80. {
  81. x=i;
  82. y=j;
  83. }
  84. }
  85. count=BFS();
  86. printf("%d\n",count);
  87. }
  88. return 0;
  89. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注