Imagine a directed acyclic graph as follows, where:
What algorithm could I use to determine the lowest common ancestor (LCA) of two arbitrary nodes, for example, the common ancestor of:
Note:
Given a Weighted Directed Acyclic Graph and a source vertex in the graph, find the shortest paths from given source to all other vertices. Try It! For a general weighted graph, we can calculate single source shortest distances in O(VE) time using Bellman–Ford Algorithm.
In ontologies, the lowest common ancestor is also known as the least common ancestor. In a tree data structure where each node points to its parent, the lowest common ancestor can be easily determined by finding the first intersection of the paths from v and w to the root.
The ancestors of a vertex v in a DAG is the set of all vertices v' != v such that v is reachable from v'. So in your example, the ancestors of 3 would be 1, 2, 4 and 5.
Den Roman's link (Archived version) seems promising, but it seemed a little bit complicated to me, so I tried another approach. Here is a simple algorithm I used:
Let say you want to compute LCA(x,y) with x and y two nodes. Each node must have a value color
and count
, resp. initialized to white and 0.
count
by oneEach red node having a count
value set to 0 is a solution.
There can be more than one solution, depending on your graph. For instance, consider this graph:
LCA(4,5) possible solutions are 1 and 2.
Note it still work if you want find the LCA of 3 nodes or more, you just need to add a different color for each of them.
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