DFS&&BFS模板
2017-04-02 17:24
253 查看
DFS模板
#include<cstdio> #include<cstring> #include<cstdlib> using namespace std; const int maxn=100; bool vst[maxn][maxn]; // 访问标记 int map[maxn][maxn]; // 坐标范围 int dir[4][2]= {0,1,0,-1,1,0,-1,0}; // 方向向量,(x,y)周围 的四个方向 bool CheckEdge(int x,int y) // 边界条件和约束条件的判断 { if(!vst[x][y] && ...) // 满足条件 return 1; else // 与约束条件冲突 return 0; } v oid dfs(int x,int y) { vst[x][y]=1; // 标记该节点被访问过 if(map[x][y]==G) // 出现目标态G { ...... // 做相应处理 return; } for(int i=0; i<4; i++) { if(CheckEdge(x+dir[i][0],y+dir[i][1])) // 按照规则 生成下一个节点 dfs(x+dir[i][0],y+dir[i][1]); } r eturn; // 没有下层搜索节点,回溯 } i nt main() { ...... return 0; }
BFS模板
1. #include<cstdio> 2. #include<cstring> 3. #include<queue> 4. #include<algorithm> 5. using namespace std; 6. const int maxn=100; 7. bool vst[maxn][maxn]; // 访问标记 8. int dir[4][2]={0,1,0,-1,1,0,-1,0}; // 方向向量 9. 10. struct State // BFS 队列中的状态数据结构 11. { 12. int x,y; // 坐标位置 13. int Step_Counter; // 搜索步数统计器 14. }; 15. 16. State a[maxn]; 17. 18. boolCheckState(State s) // 约束条件检验 19. { 20. if(!vst[s.x][s.y] && ...) // 满足条件 21. return 1; 22. else // 约束条件冲突 23. return 0; 24. } 25. 26. void bfs(State st) 27. { 28. queue <State> q; // BFS 队列 29. State now,next; // 定义2 个状态,当前和下一个 30. st.Step_Counter=0; // 计数器清零 31. q.push(st); // 入队 32. vst[st.x][st.y]=1; // 访问标记 33. while(!q.empty()) 34. { 35. now=q.front(); // 取队首元素进行扩展 36. if(now==G) // 出现目标态,此时为Step_Counter 的最小值,可以退出即可 37. { 38. ...... // 做相关处理 39. return; 40. } 41. for(int i=0;i<4;i++) 42. { 43. next.x=now.x+dir[i][0]; // 按照规则生成 下一个状态 44. next.y=now.y+dir[i][1]; 45. next.Step_Counter=now.Step_Counter+1; // 计数器加1 46. if(CheckState(next)) // 如果状态满足约束条件则入队 47. { 48. q.push(next); 49. vst[next.x][next.y]=1; //访问标记 50. } 51. } 52. q.pop(); // 队首元素出队 53. } 54. return; 55. } 56. 57. int main() 58. { 59. ...... 60. return 0; 61. }
相关文章推荐
- HDU 1532 Drainage Ditches(增广路dfs&bfs模板)
- DFS&&BFS模板
- BFS&&DFS模板
- POJ1979 FLIP GAME (DFS&BFS都可以)
- HDOJ 1312 DFS&BFS
- HNCU1103:红与黑(BFS&DFS)
- 【算法模板之DFS和BFS】
- BFS和DFS模板
- DFS & BFS
- hdu 4771 Stealing Harry Potter's Precious (2013 杭州 onsite B题)bfs预处理后,dfs枚举或tsp
- zoj3736(bfs&&dfs)
- 递归,回溯,DFS,BFS的理解和模板【摘】
- 算法学习笔记(一):拓扑排序与传递闭包(通过bfs&&dfs)
- BFS/DFS 模板 代码
- DFS & BFS
- fw -BFS & DFS tree-2-013年12月17日17:56:33
- DFS&BFS(链式前向星实现)
- Graph Algorithms: Implementation& DFS& Strong Component& BFS & Dijkstra & Bellman Ford
- 第三次组队赛 (DFS&BFS)
- 【二分图匹配】最大匹配-匈牙利算法BFS && DFS写法