I need to find an algorithm for finding all the roots in a directed graph, in O(n+m).
I have an algorithm for finding a single root:
Now if I want to find all the roots, is the best way to just run the above algorithm O(n) times, on a different vertex in the last tree every time ? Assuming I found a root, if another root exists then it must be on the last tree, then is it O(n+m) if I continue to run the above algorithm until receiving "no root exists" or until going over all vertices ?
Thanks in advance !
Two approaches:
Reverse the graph and calculate DFS-loop() and note the vertices which have no outgoing edges (like Abhishek said).
More efficient - Run DFS-loop() on the graph and keep track of vertices with no incoming edges using a true, false table.
Method 1 takes twice as long in the worst case.