Graph - adjacency list - BFS
/***
Graph based - BFS
***/
// adjacent list represented graph
class graph
{
int V;
// # of vertices
list<int>
*adj; //Pointer to an array containing adjacency lists
void
BFSUtil(int v, queue<int> &bfsqueue);
public:
graph(int
V);
void
add_edge(int v, int w); //edge between w and v
void
BFS(int v);
};
graph::graph(int V)
{
this->V = V;
adj = new
list<int>[V];
}
void graph::add_edge(int v, int w)
{
adj[v].push_back(w); // Add w to v’s list.
}
void graph::BFSUtil(int v, queue<int> bfsgraph, bool
*visited) {
list<int>::iterator
it;
while(!bfsgraph.empty())
{
int
n = bfsgraph.front();
cout<<
n <<" ";
bfsgraph.pop();
for(it
= adj[v].begin(); it != adj[v].end(); it++) {
if(!visited[*it])
{
bfsgraph.push(*it);
visited[*it]
= true;
}
}
}
}
void graph::BFS() {
//mark
all the vertices as not visited
bool
*visited = new bool[V];
for(int
i = 0; i<V; i++) visited[i] = false;
queue<int>
bfsgraph;
for(int
i=0; i<V; i++) {
if(!visited[i])
{
visited[v]
= true;
bfsgraph.push(v);
BFSUntil(i, bfsgraph, visited);
}
}
}
Comments
Post a Comment