您的位置:首页 > 其它

宽度优先搜索(BFS)

2016-07-12 14:31 204 查看
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
;
edges = new vector<int>
;
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特性,或者可以用上边注释部分
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: