宽度优先搜索(BFS)
来源:互联网 发布:临汾行知学校马俊峰 编辑:程序博客网 时间:2024/06/05 07:09
BFS,其英文全称是Breadth First Search。
0 1 4 2 3
思路:
从图中某个节点出发,将该结点入队,标记为已访问。然后输出队列的队首(第一次为起点),将队首从队列中删除,访问该结点的邻接表,将未标记的相邻结点入队,并且标记为已访问。接下来循环操作第二句话。
按照上边的图,假设出发点为0。0入队,将0标记为已访问,输出0,将0从队列中删除,访问0的邻接表,将1和4入队,并且都标记为已访问。那么,接下来,队首为1,输出1,将1从队列中删除,访问1的邻接表,将2和3入队。此时队首为4,输出4,将4从队列中删除,4的邻接表为空。此时队列不为空,队首为2,将2输出,将2从队中删除,2的邻接表为空,将3输出,将3从队中删除,3的邻接表为空,队列为空,完成遍历。
代码:
#include <iostream>#include <cstring>#include <cstdlib>#include <vector>#include <queue>using namespace std;class Graph{private: int n; bool *visited; //代表节点是否被访问 vector<int> *edges; //邻接表public: Graph(int _n){ n = _n; visited = new bool[n]; edges = new vector<int>[n]; memset(visited, 0, sizeof(visited)); } ~Graph(){ delete []visited; delete []edges; } void myInsert(int x, int y){ edges[x].push_back(y); edges[y].push_back(x); } void bfs(int startNode){ queue<int> bfsQueue; bfsQueue.push(startNode); visited[startNode] = true; while(!bfsQueue.empty()){ int temp = bfsQueue.front(); cout<<temp<<endl; bfsQueue.pop();// vector<int>::iterator it;// for(it = edges[temp].begin(); it!=edges[temp].end(); it++){// if(!visited[*it]){// bfsQueue.push(*it);// visited[*it] = true;// }// } //c++11特性,或者可以用上面注释的写法 for(int i:edges[temp]){ if(!visited[i]){ bfsQueue.push(i); visited[i] = true; } } } }};int main(){ int n, m, k; cin>>n>>m; //n个节点 Graph g(n); //m条边 for(int i=0; i<m; i++){ int x, y; cin>>x>>y; g.myInsert(x, y); } //输入bfs开始的点 cin>>k; g.bfs(k); system("pause"); return 0;}
其中有使用c++11特性,或者可以用上边注释部分
0 0
- 宽度优先搜索(BFS)
- BFS(宽度优先搜索)
- 宽度优先搜索(BFS)
- 宽度优先搜索 BFS
- 宽度优先搜索BFS
- 宽度优先搜索bfs
- poj 3278(bfs宽度优先搜索)
- 图论(四)宽度优先搜索BFS
- BFS宽度优先搜索思想
- 广度/宽度优先搜索(BFS)
- 广度/宽度优先搜索(BFS)
- BFS宽度优先搜索算法
- BFS宽度优先搜索思想
- 广度/宽度优先搜索(BFS)
- BFS宽度优先搜索思想
- 广度/宽度优先搜索(BFS)
- 广度/宽度优先搜索(BFS)
- 广度/宽度优先搜索(BFS)
- centos6.7上使用nginx实现负载均衡
- C#正则获取网页的网址和名称
- javascript第二天
- python+selenium调用浏览器(IE-Chrome-Firefox)实现爬虫功能
- linux 修改用户密码
- 宽度优先搜索(BFS)
- socket编程总结(八)bind()
- caffe学习系列:计算图片数据的均值
- Java注解学习四:@Inherited的使用
- iOS动画(Core Animation)使用
- 深入浅出UML类图
- 域名解析中A记录、CNAME、MX记录、NS记录的区别和联系
- 将项目放在不同系统环境下出现编码格式错误
- java.lang.NumberFormatException: multiple points已解决