hdu 1072

  1. #include <set>
  2. #include <iostream>
  3. #include <vector>
  4. #include <algorithm>
  5. #include <stdlib.h>
  6. #include <math.h>
  7. #include <string.h>
  8. #include <queue>
  9. using namespace std;
  10. #define MAX 300
  11. int map[MAX][MAX];
  12. bool visit[MAX][MAX]; // 访问标记
  13. int dir[4][2] = {0, 1, 0, -1, 1, 0, -1, 0}; // 方向向量 右,左,下,上
  14. int num;
  15. struct data // BFS队列中的状态数据结构
  16. {
  17. int x, y; // 坐标位置
  18. int step; // 搜索步数统计器
  19. int state;
  20. }start, over;
  21. void input_bfs(int row, int column)
  22. {
  23. int flag =0;
  24. int state;
  25. for(int i=1; i<=row; i++)
  26. for(int j=1; j<=column; j++)
  27. {
  28. scanf("%d", &state);
  29. if(state == 2)
  30. {start.x = i; start.y = j; start.state = 2;}
  31. else if(state == 3)
  32. {over.x = i; over.y =j; over.state = 3;}
  33. map[i][j] = state;
  34. }
  35. }
  36. void initialize(int row, int column)
  37. {
  38. memset(map, 0, sizeof(map) );
  39. memset(visit, false, sizeof(visit) );
  40. for(int i=1; i<=row; i++)
  41. for(int j=1; j<=column; j++)
  42. visit[i][j] = true;
  43. num = 0;
  44. }
  45. bool check_bfs(data temp)
  46. {
  47. if(visit[temp.x][temp.y] && map[temp.x][temp.y] ) // 满足条件,根据条件添加
  48. return 1;
  49. else return 0;
  50. }
  51. void bfs(data first)
  52. {
  53. queue<data> que; // BFS队列
  54. data now, next; // 定义2个状态,当前和下一个
  55. first.step = 0; // 计数器清零
  56. int begin = 0;
  57. que.push(first);
  58. visit[first.x][first.y] = 0;
  59. while(!que.empty() )
  60. {
  61. now = que.front(); // 取队首元素进行扩展
  62. if(now.step !=begin) {begin = now.step; num++;}
  63. if(now.x == over.x && now.y == over.y) // 出现目标态,此时为Step的最小值,可以退出即可
  64. {
  65. over.step = now.step; // 做相关处理
  66. return ;
  67. }
  68. if(map[now.x][now.y] == 4 && now.step < 6)
  69. now.step = 0;
  70. for(int i=0; i<4; i++)
  71. {
  72. next.x = now.x + dir[i][0];
  73. next.y = now.y + dir[i][1];
  74. next.step = now.step +1;
  75. if(check_bfs(next) ) // 如果状态满足约束条件则入队
  76. {
  77. que.push(next);
  78. visit[next.x][next.y] = 0;
  79. }
  80. }
  81. que.pop(); // 队首元素出队
  82. }
  83. return ;
  84. }
  85. int main()
  86. {
  87. freopen("read.txt", "r", stdin);
  88. int T;
  89. scanf("%d", &T);
  90. while(T--)
  91. {
  92. int row, column;
  93. scanf("%d%d", &row, &column);
  94. initialize(row, column);
  95. input_bfs(row, column);
  96. bfs(start);
  97. if(over.step < 6)
  98. printf("%d ", num);
  99. else printf("-1 ");
  100. }
  101. return 0;
  102. }





附件列表

    原文地址:https://www.cnblogs.com/sober-reflection/p/264732a7cd90031f437bf1f1148103b1.html