dfs bfs模板

  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 Goal_dfs 2
  11. #define MAX 300
  12. int map[MAX][MAX];
  13. bool visit[MAX][MAX]; // 访问标记
  14. int dir[4][2] = {0, 1, 0, -1, 1, 0, -1, 0}; // 方向向量
  15. struct data // BFS队列中的状态数据结构
  16. {
  17. int x, y; // 坐标位置
  18. int step; // 搜索步数统计器
  19. }seat[MAX];
  20. void input_dfs(int row, int column)
  21. {
  22. int temp;
  23. for(int i=0; i<row; i++)
  24. for(int j=0; j<column; j++)
  25. {
  26. // if(); scanf("%c",&temp); //目标或者起点条件
  27. scanf("%d", &temp);
  28. }
  29. }
  30. void input_bfs()
  31. {}
  32. void initialize(int row, int column)
  33. {
  34. memset(map, 0, sizeof(map) );
  35. memset(visit, false, sizeof(visit) );
  36. for(int i=1; i<=row; i++)
  37. for(int j=1; j<=column; j++)
  38. visit[i][j] = true;
  39. }
  40. bool check_dfs(int x, int y)
  41. {
  42. if(!visit[x][y]) return 1; // 满足条件
  43. else return 0;
  44. }
  45. bool check_bfs(data temp)
  46. {
  47. if(visit[temp.x][temp.y]) // 满足条件,根据条件添加
  48. return 1;
  49. else return 0;
  50. }
  51. void dfs(int x, int y)
  52. {
  53. visit[x][y] = 1; // 标记该节点被访问过
  54. if(map[x][y] == Goal_dfs) // 出现目标态Goal
  55. {
  56. //(); 做相应处理
  57. return ;
  58. }
  59. for(int i=0; i<4; i++)
  60. {
  61. if( check_dfs(x+dir[i][0], y+dir[i][1]) ) // 按照规则生成下一个节点
  62. dfs(x+dir[i][0],y+dir[i][1]);
  63. }
  64. return ; // 没有下层搜索节点,回溯
  65. }
  66. void bfs(data first)
  67. {
  68. queue<data> que; // BFS队列
  69. data now, next; // 定义2个状态,当前和下一个
  70. first.step = 0; // 计数器清零
  71. que.push(first);
  72. visit[first.x][first.y] = 1;
  73. while(!que.empty() )
  74. {
  75. now = que.front(); // 取队首元素进行扩展
  76. /*
  77. if(now = goal) // 出现目标态,此时为Step_Counter的最小值,可以退出即可
  78. {
  79. (); // 做相关处理
  80. return ;
  81. }
  82. */
  83. for(int i=0; i<4; i++)
  84. {
  85. next.x = now.x + dir[i][0];
  86. next.y = now.y + dir[i][1];
  87. next.step = now.step +1;
  88. if(check_bfs(next) ) // 如果状态满足约束条件则入队
  89. {
  90. que.push(next);
  91. visit[next.x][next.y] = 1;
  92. }
  93. }
  94. que.pop(); // 队首元素出队
  95. }
  96. return ;
  97. }
  98. int main()
  99. {
  100. return 0;
  101. }





附件列表

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