I have an adjacency list for a DAG, and I need to find all connected nodes from all nodes, for example : for a DAG below
1 -> 3 -> 4
2 -> 4
3 -> 2
4 -> 5
5 -> NULL
I need this :
1 -> {2, 3, 4, 5}
2 -> {4, 5}
3 -> {2, 4, 5}
4 -> {5}
5 -> NULL
Is there any efficient algorithm for this ?
As you mentioned a DAG you can use following algorithm to get all connected components to given vertex :-
- Do a Topological Sort of the all nodes in graph
- Start in decreasing order of the sorted nodes.
- Maintain a Set of all connected nodes for each node.
- Sort adjacency list of vertex u in toposort order
- For vertex u and each edge(u,v) and !Set(u).contains(v) do Set(u) = Set(u) union Set(v) union v
- Do this for all node in decreasing order of toposort.
Time Complexity :-
Toposort : O(E)
Caculating Set : O(V^2*logV)
Total: O(V^2*logV)
Example:-
1 -> 3 -> 4
2 -> 4
3 -> 2
4 -> 5
5 -> NULL
TopoSort: 1,3,2,4,5
Visiting in descending order :-
1. Set(5) = {null}
2. Set(4) = Set(5) + 5 = {5}
3. Set(2) = Set(4) + 4 = {4,5}
4. Set(3) = Set(2) + 2 = {2,4,5}
5. Set(1) = Set(3) + 1 = {1,2,4,5}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With