Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find all connected nodes in adjacency list

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 ?

like image 996
Happy Mittal Avatar asked Oct 18 '25 10:10

Happy Mittal


1 Answers

As you mentioned a DAG you can use following algorithm to get all connected components to given vertex :-

  1. Do a Topological Sort of the all nodes in graph
  2. Start in decreasing order of the sorted nodes.
  3. Maintain a Set of all connected nodes for each node.
  4. Sort adjacency list of vertex u in toposort order
  5. For vertex u and each edge(u,v) and !Set(u).contains(v) do Set(u) = Set(u) union Set(v) union v
  6. 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} 
like image 101
Vikram Bhat Avatar answered Oct 20 '25 01:10

Vikram Bhat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!