0

I'm unsure of how to deal with the input I've been provided for an assignment on Breadth First Search. We're suppose to traverse a graph and output the order of traversal. Here's a list of directed edges:

0 1
0 2
2 6
6 1
7 9
4 0
6 4
6 3
9 3
6 2
8 6
1 4
5 6
1 2
6 5
2 3
2 7
5 7
9 0

Traversal: 0 1 2 4 6 3 7 9 5

I'm not sure how to traverse it correctly? Once I get to Node 1 & 2 how do I get to the other Node 1's & 2's that are further down on the list?

I know I'll have to keep track of the nodes using separate lists (which is a separate issue) but would it be best to order the list first?

Not really looking for code just a starting point but if you'd like to answer with a code example, circular linked list in C++ is what I have to work with.

1 Answer 1

1

If you want to traverse with BFS, you need to use a queue structure: For Example:

  • Take First Node (0).
  • Put (0) Node into queue.
  • Repeat this process, until queue not empty.

    1. Dequeue (0)
    2. Check children of Node (0) if Not yet Visited
      1. According to your input ("0 1") edge means its only children is 1 so put 1 into queue.
    3. Print (i.e. is 0).

    end loop end

In other words. Next iteration will be 1 have two children i.e 1 (2) and 1 (4) put all children into queue and dequeue the 1 and print. Next iteration will be, dequeue the 2, have three children i.e 2 (6), 2 (3) and 2 (7) put all children into queue and print 2. Next iteration will be dequeue the 4, have only single child i.e 4 (0) but you already print and visit the 0 so simply print 4.

you can use this queue structure. For input you can use linklist, array, or structure.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the response! I can't wrap my head around how I'm going to jump to the correct children otherwise. For example when I dequeue the 2 how will I know the 3 and 7 are the children since they are further down? I've put everything on the queue using a linked list for now and it looks something like this 0102266179... So is it best to re-order the list first?
Use structure instead of linklist for input graph, [link(stackoverflow.com/questions/18006755/…). something like that
you dont need to order anything if you check your input, every node have children means linklist must point to child nodes. but the single node have multiple children. and linklist does not have ability to point more than one child.
oR if you still want to use llinklist put node value into linklist value and put children for your pointer. store all, check if all node value is equal same means 2 then enqueue the pointer nodes into queue

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.