1

I have the following directed graph implementation

 Nodes nod[]
 List<Arcs> arc[]

So the node on the n'th position has all his arcs of the list in position n. Of course, the nodes are organized accordingly, so that I can use Binary Search. Based on this implementation. I wish to create a DFS algorithm. I know very well the pseudo code, adapting to java shouldn't be a problem.

But my question is the following. In DFS we need to start searching from the "top" node. And thinking about it, i dont have this "top" node. Moreover, I have no idea how to get it. So I ask, how do i get this top node, considering my implementation?

Thanks for the help.

14
  • So are all the Nodes in the array considered top level nodes? Commented Oct 12, 2012 at 19:58
  • Refer this:- stackoverflow.com/questions/10258204/… Commented Oct 12, 2012 at 19:59
  • @Brad No no. Thats the problem. Its a normal graph. And i need to find the top node Commented Oct 12, 2012 at 19:59
  • @RahulTripathi Not really answering my question. Commented Oct 12, 2012 at 20:02
  • 3
    Assuming that the root node is not in a known position (first, middle, whatever) I suppose you'd have to look for the node that doesn't have an arc going to it. Commented Oct 12, 2012 at 20:03

2 Answers 2

2

Expanding on my comment:

Assuming that the arcs are directed (i.e., from the parent node to the child only) you can search all of the nodes for the one with no incoming arcs:

// parent_count is an integer array of the same size as nod[]

for i = 1..n
    for each arc in arc[i] (arc going from i to j)
        increment parent_count[j]
    end
end

for k = 1..n
    if parent_count[k] == 0
        return k
end
Sign up to request clarification or add additional context in comments.

Comments

0

DFS/BFS are very common and general algorithms to travel over the graph, both has no special meaning of top node, you could start DFS from any node. For example, DFS is used in topological sort algorithm and it states that we have to start from nodes with no incoming edges.

Could you please highlight what problem you want to solve? This should help us to find nodes that has to be used as a roots for DFS.

1 Comment

yes you are correct. You can choose any node and DFS will search. But in this particular case i want to start searching from the top node for particular reason. Still i was given a solution how to find the top node.

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.