You are not logged in. Please login at to post your questions!


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 . Thanks.

asked 14 Jul '14, 14:20

shantanu10's gravatar image

accept rate: 0%

Why the downvote ?

(14 Apr '16, 17:48) shubham992★

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<int> 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<int> to store a queue.. Hope you have followed it.. :)


answered 14 Jul '14, 14:56

skrcode's gravatar image

accept rate: 18%

havent u ever heard about geeks for geeks??? btw...this will help...:)


answered 14 Jul '14, 14:47

kunal361's gravatar image

accept rate: 21%

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 ?

(14 Jul '14, 14:57) shantanu102★

this will help u getting to know about stl...

(14 Jul '14, 15:03) kunal3614★

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


answered 14 Apr '16, 17:20

vatsalsharma_3's gravatar image

accept rate: 11%


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


answered 26 Jul '14, 09:04

crazycoder89's gravatar image

accept rate: 0%

toggle preview

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here



Answers and Comments

Markdown Basics

  • *italic* or _italic_
  • **bold** or __bold__
  • link:[text]( "title")
  • image?![alt text](/path/img.jpg "title")
  • numbered list: 1. Foo 2. Bar
  • to add a line break simply add two spaces to where you would like the new line to be.
  • basic HTML tags are also supported
  • mathemetical formulas in Latex between $ symbol

Question tags:


question asked: 14 Jul '14, 14:20

question was seen: 14,113 times

last updated: 14 Apr '16, 17:48