Reputation: 11
Say we have a DAG comprised of a list of nodes A, B, C, D, and E.
Each node has a list of reachable nodes - for example:
A --> B, C
A --> B
D --> E
In this case, we would have to visit nodes A and D to comprehensively visit all nodes in the graph. What is the best algorithm to approach this problem in general?
Upvotes: 1
Views: 160
Reputation: 2777
Here is a linear approach:
Time Complexity(N + M) - linear in graph size
Upvotes: 2
Reputation: 650
Here is an approach.
Let's say that node A
is parent of node B
if there is an arc from A
to B
.
And node C
is the most-parent of node B
, if it has no parent and there is a path from C
to B
.
Mark every node as not visited
.
For every node in DAG you define it's parent.
for every node A
that is not visited
Find A
's most-parent MP
Mark all nodes that are reachable from MP
as visited
Put MP
to array
After this you'll get smallest subset of nodes that reach all nodes in DAG in array
Time compexity of algo is O(n^2)
Upvotes: 1