#include <vector>
#include <queue>
#include <iostream>
#include <map>
#include <limits.h>
using namespace std;
enum{WHITE,GRAY,BLACK};
struct Vertex
{
int color;
int d;
int pre;
Vertex()
:pre(-1),color(WHITE),d(INT_MAX)
{ }
};
class bfsGraph
{
public:
bfsGraph(int n)
:vertexNum(n),vertexs(n)
{ }
int addEdge(int i,int j)
{
adj[i].push_back(j);
adj[j].push_back(i);
return 0;
}
int bfs(int start)
{
for(int i=0;i!=vertexNum;i++)
{
vertexs[i].color=WHITE;
vertexs[i].d=INT_MAX;
vertexs[i].pre=-1;
}
vertexs[start].color=GRAY;
vertexs[start].d=0;
vertexs[start].pre=-1;
q.push(start);
while(!q.empty())
{
int u=q.front();
q.pop();
for(auto v:adj[u])
{
if(vertexs[v].color==WHITE)
{
vertexs[v].color=GRAY;
vertexs[v].d=vertexs[u].d+1;
vertexs[v].pre=u;
q.push(v);
}
}
vertexs[u].color=BLACK;
}
cout<<"set ok"<<endl;
return 0;
}
int printPath(int v,int start)
{
cout<<"The total length is :"<<vertexs[v].d<<endl;
cout<<"The Path is: "<<endl;
do
{
cout<<v<<endl;
v=vertexs[v].pre;
}while(v!=-1);
return 0;
}
int printAdj()
{
for(auto k:adj)
{
cout<<k.first<<": ";
for(auto v:k.second)
cout<<v<<" ";
cout<<endl;
}
return 0;
}
private:
int vertexNum;
vector<Vertex> vertexs;
map<int,vector<int>> adj;
queue<int>q;
};
测试cpp
#include <vector>
#include <iostream>
#include "bfs.h"
using namespace std;
int main()
{
bfsGraph mybfs(8);
mybfs.addEdge(0,1);
mybfs.addEdge(1,2);
mybfs.addEdge(2,3);
mybfs.addEdge(3,4);
mybfs.addEdge(3,5);
mybfs.addEdge(4,5);
mybfs.addEdge(4,6);
mybfs.addEdge(4,7);
mybfs.addEdge(5,6);
mybfs.addEdge(6,7);
mybfs.printAdj();
mybfs.bfs(2);
mybfs.printPath(7,2);
return 0;
}