1、邻接矩阵版BFS
int n;
int G[maxv][maxv];
bool inq[maxv]={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)
{
BFS(q);
}
}
}
2、邻接表版BFS
vector<int> adj[maxv];
int n;
bool inq[maxv]={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()
{
for(int u=0;u<n;u++)
{
if(inq[u]==false)
{
BFS(u);
}
}
}
3、增加了层次信息的邻接表BFS
struct Node
{
int v;
int layer;
};
vector<Node> adj[maxv];
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;
}
}
}
}