How to implement bfs,dfs in C++

I am facing difficulty in implementing bfs in C++ . I know the algorithm but having problem in implementing it on the problems. Is there any book/tutorial which can help me out . Please suggest something .

havent u ever heard about geeks for geeks??? btw…this will help…:slight_smile:

1 Like

I won’t give you the code, but I will tell how to go about implementing it. Learn STL. Makes it very easy to store graphs. Use this to store graphs -> vector < vector < int > > AdjList(N) (You can use a pair if edge weights have to be stored along with the edges). The above code means that that for each node, you store the list of the nodes it is connected to, something like a lists of lists… where the outside list is list of all nodes and inside list is a list of all nodes connected to the specific node of the outside list. So now dfs,bfs etc becomes trivial. Learn how to traverse a container, like this -> for(vector iterator :: it = v.begin();it!=v.end();it++). This traverses a vector of ints named v. Do this for all nodes(in case of dfs, if it is not visited before).In case of bfs, use queue to store a queue… Hope you have followed it… :slight_smile:

1 Like

I dont have any idea of the STL(list) used their and additionally I dont know what is the role of the syntax like ‘new’ , ‘this’ which are present in that program ?

this will help u getting to know about stl…

Mohit Menghnani : Try using for your coding issues. It will help you in the long run.

If you are not getting the OOP concept or STL then you might want to take a look here:
Its super short and cool
link text

Why the downvote ?