图的dfs与bfs(深搜广搜)c++实现
来源:互联网 发布:数据成熟度模型 编辑:程序博客网 时间:2024/06/10 16:37
以下是基于图的链表表示的:
dfs和bfs的演示:
http://sjjg.js.zwu.edu.cn/SFXX/sf1/gdyxbl.html (深搜)
http://sjjg.js.zwu.edu.cn/SFXX/sf1/sdyxbl.html (广搜)
bfs通过检测边发现点,被发现点(但未探索)入队。(被探索是指是否检测过与该点相关联的临近顶点)一个顶点被完全探索当且仅当他的所有边被检测。一个顶点探索完选另一个顶点,被选点应位于被发现但未被探索点队列的队首。待探索点集为空时算法结束。(bfs探索顺序与发现顺序一致,dfs发现后马上探索)
1 #include <iostream> 2 #include <cstdio> 3 #include <list> 4 #include <vector> 5 #include <queue> 6 using namespace std; 7 int n; 8 vector< list<int> > graph; 9 bool visited[100] = {0};10 void dfs(int v)11 {12 list<int>::iterator it;13 visited[v] = true;14 printf("%5d", v);15 for (it = graph[v].begin(); it != graph[v].end(); ++it)16 if (!visited[*it])17 dfs(*it);18 }19 void bfs(int v)20 {21 list<int>::iterator it;22 printf("%5d", v);23 visited[v] = true;24 queue<int> t;25 t.push(v);26 while (!t.empty())27 {28 v = t.front();29 t.pop();30 for (it = graph[v].begin(); it != graph[v].end(); ++it)31 if (!visited[*it])32 {33 printf("%5d", *it);34 t.push(*it);35 visited[*it] = true;36 }37 }38 cout << endl;39 }40 int main()41 {42 //freopen("in.txt", "r", stdin);43 cout << "input the vertex num:"<< endl;44 cin >> n;45 vector< list<int> >::iterator it;46 for (int i = 0; i < n; ++i)47 {48 list<int> il;49 int t;50 while (cin >> t && t != n)51 il.push_back(t);52 graph.push_back(il);53 }54 cout << "result for bfs:" << endl;55 bfs(0);56 memset(visited, 0, sizeof(visited)); //重新初始化标志数组57 cout << "result for dfs:" << endl;58 dfs(0);59 system("pause");60 return 0;61 }
按照链表表示输入以下数据:
8
0 1 2 8
1 0 3 4 8
2 0 5 6 8
3 1 7 8
4 1 7 8
5 2 7 8
6 2 7 8
7 3 4 5 6 8
最后一个8用来标识这个节点输入结束。可以得到深搜和广搜的结果。
- 图的dfs与bfs(深搜广搜)c++实现
- 图的dfs与bfs(深搜广搜)c++实现
- 图的dfs与bfs(深搜广搜)c++实现
- [数据结构]图基于邻接矩阵的BFS与DFS的C语言简单实现
- 图的遍历(DFS与BFS)
- C语言实现图的邻接矩阵和BFS DFS
- 图的BFS与DFS
- dfs与bfs实现
- DFS与BFS的代码实现
- 数据结构与C语言实现(九)——图(上):邻接表,DFS与BFS
- 【数据结构与算法】自己动手实现图的BFS和DFS(附完整源码)
- 【数据结构与算法】自己动手实现图的BFS和DFS(附完整源码)
- 【数据结构与算法】自己动手实现图的BFS和DFS(附完整源码)
- 【数据结构与算法】自己动手实现图的BFS和DFS(附完整源码)
- 深度遍历(DFS)与广度遍历(BFS) (C语言实现)
- c++:DFS与BFS详解
- 【图】BFS与DFS
- 有向图的DFS和BFS(邻接矩阵实现)
- hdu 1241 Oil Deposits(dfs入门)
- DFS中的奇偶剪枝(转自chyshnu)
- hdu 1010 Tempter of the Bone(dfs+奇偶剪枝)
- hdu 1312 Red and Black(dfs入门)
- ural 1033. Labyrinth(dfs)
- 图的dfs与bfs(深搜广搜)c++实现
- hdu 1209 Clock(水题)
- ural 1024. Permutations
- hdu 1518 Square(dfs)
- bjfu 1143 小蝌蚪安家(bfs入门)
- 并查集入门
- hdu 1026 Ignatius and the Princess I(bfs+priority_queue)
- ural 1910. Titan Ruins: Hidden Entrance(Titan Ruins系列题目)
- C++函数对象count_if用法(转)