图的dfs与bfs(深搜广搜)c++实现
来源:互联网 发布:苹果官方同步软件 编辑:程序博客网 时间:2024/06/03 13:39
#include <iostream>#include <cstdio>#include <list>#include <vector>#include <queue>using namespace std;int n;vector< list<int> > graph;bool visited[100] = {0};void dfs(int v){ list<int>::iterator it; visited[v] = true; printf("%5d", v); for (it = graph[v].begin(); it != graph[v].end(); ++it) if (!visited[*it]) dfs(*it);}void bfs(int v){ list<int>::iterator it; printf("%5d", v); visited[v] = true; queue<int> t; t.push(v); while (!t.empty()) { v = t.front(); t.pop(); for (it = graph[v].begin(); it != graph[v].end(); ++it) if (!visited[*it]) { printf("%5d", *it); t.push(*it); visited[*it] = true; } } cout << endl;}int main(){ //freopen("in.txt", "r", stdin); cout << "input the vertex num:"<< endl; cin >> n; vector< list<int> >::iterator it; for (int i = 0; i < n; ++i) { list<int> il; int t; while (cin >> t && t != n) il.push_back(t); graph.push_back(il); } cout << "result for bfs:" << endl; bfs(0); memset(visited, 0, sizeof(visited)); //重新初始化标志数组 cout << "result for dfs:" << endl; dfs(0); system("pause"); return 0;}
按照链表表示输入以下数据:
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用来标识这个节点输入结束。可以得到深搜和广搜的结果。
0 0
- 图的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(邻接矩阵实现)
- SICP 习题 (2.20)解题总结: 不确定数量参数
- Maven使用
- C语言实现简单线程池
- 图的单源最短路径Dijkstra算法
- Struts2源码学习笔记(一)
- 图的dfs与bfs(深搜广搜)c++实现
- jQuery_1_总体架构&自调用匿名函数
- SICP 习题 (2.21)解题总结: map的使用
- POJ3187 Backward Digit Sums
- Openstack Cinder概念及规划
- ant的使用
- Win XP后的五个设置技巧
- 从《绝命毒师》看研发人员的自我管理
- minSdkVersion 14 cannot be smaller than version L declared in library com.android.support:support-