跟树的层序遍历很像,主要就是使用队列,从内到外一层一层的遍历
伪代码:
BFS(u){
queue q;
将u入队;
inq[u] = true; //设置u已被加入过队列
while(q非空){
取出q的队首元素u进行访问;
for(从u出发可达到的所有顶点v){
if(inq[v] == false ){
将v入队;
inq[v] = true;
}
}
}
}
BFSTrave(G){ //遍历图
for(G的所有顶点u){ //枚举G的所有顶点u
if(inq[u] == false){ //如果u未曾加入过队列
BFS(u); //遍历u所在的连通块
}
}
}
邻接矩阵版:
#include <stdio.h>
#include <stdlib.h>
#include <queue>
using namespace std;
const int maxn = 1000;
const int INF = 100000000;
int n,G[manx][maxn];
bool inq[maxn] = {false};
void BFS(int u){
queue<int>q;
q.push(u);
inq[u] = true;
while(!q.empty()){
int u = q.front();
q.pop();
for(int v = 0;v <n;v++){
if(inq[v] == false && G[u][v] != INF){
q.push(v);
inq[v] = true;
}
}
}
}
void BFSTrave(){
for(int u = 0;u <n;u++){ //枚举所有顶点
if(inq[u] == false){ //如果u未曾加入过队列
BFS(q); //遍历u所在的连通块
}
}
}
邻接表版:
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <queue>
using namespace std;
const int maxn = 100;
const int INF = 10000000;
vector<int> Adj[maxn]; //图G,Adj[u]从顶点u出发可以到达的所有顶点
int n; //n为顶点数,maxn为最大顶点数
bool inq[maxn] = {false};
void BFS(int u){
queue<int> q;
q.push(u);
inq[u] = true;
while(!q.empty()){
int u = q.front();
q.pop();
for(int i = 0;i <Adj[u].size();i++){
int v = Adj[u][i];
if(inq[v] == false){
q.push(v);
inq[v] = true;
}
}
}
}
void BFSTrave(){ //遍历图G
for(int u = 0;u <n;u++){ //枚举所有顶点
if(inq[u] == false){ //如果u未曾加入过队列
BFS(q); //遍历u所在的连通块
}
}
}
输出层号:
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <queue>
using namespace std;
const int maxn = 100;
const int INF = 10000000;
vector<int> Adj[maxn]; //图G,Adj[u]从顶点u出发可以到达的所有顶点
int n; //n为顶点数,maxn为最大顶点数
bool inq[maxn] = {false};
struct Node{
int v;
int layer;
};
void BFS(int s){
queue<Node>q;
Node start;
start.v = s;
start.layer = 0;
q.push(start);
inq[start.v] = true;
while(!q.empty()){
Node topNode = q.front();
q.pop();
int u = topNode.v;
for(int i = 0;i <Adj[u].size();i++){
Node next = Adj[u][i];
next.layer = topNode.layer+1;
if(inq[next.v] == false){
q.push(next);
inq[next.v] = true;
}
}
}
}