## BFS concepts, search in a Graph

Asked By 260 points N/A Posted on -

Hi.

I am trying to understand this code:

q.push(start);
Visit [start] =1;
while(!q.empty())
{
cur=q.front();
q.pop();
process(cur);
{
}
}

Doing some BFS search. But I don't see anything that matches the text book. As far as I understood the BFS traversing searches the parent first and then from left to right the child nodes. If not found, then the leftmost becomes the parent doing the same thing.

The process continues until the Node is found. But how do I do it? Please explain the process if possible.

SHARE
Answered By 0 points N/A #92856

## BFS concepts, search in a Graph

Hello Martin,

If you have a confusion about the BFS concept, then I would suggest you to first understand it properly.

On reading this, you shall also realize the application of queues in BFS.

Answered By 260 points N/A #92857

## BFS concepts, search in a Graph

Thanks a lot.

I am clear on the concept now. But how do I apply it in the code? Will this be the algorithm something like:

q.push(start);
Visit [start] =1;
while(!q.empty())
{
cur=q.front();
q.pop();
process(cur);
{
}
}

Answered By 0 points N/A #92858

## BFS concepts, search in a Graph

It should not be much of a trouble; C++ STL is very handy for this.

Use an array of vector to store the graph as adjacency matrix and keep an array for tracking visits nodes, like

bool visit[mxNod];

Then you can just use this small function to get the adjacent nodes

{
}

So your code should look something like:

void bfsGraph(int start)
{
init();
queue <int> q;
q.push(start);
visit[start]=1;
while(!q.empty())
{
int cur=q.front();
q.pop();
process(cur);
{
{
}
}
}
}

Hope this helps.

Answered By 260 points N/A #92859

## BFS concepts, search in a Graph

Thanks, but my code gives: error: 'queue' was not declared in this scope.

Answered By 0 points N/A #92860

## BFS concepts, search in a Graph

Answered By 260 points N/A #92861

## BFS concepts, search in a Graph

Cool,

I don't know how to thank you synthesis. That was very nice of you.

Answered By 0 points N/A #92862

## BFS concepts, search in a Graph

You are most welcome.