I have a undirected acyclic graph, which expressed by adjacency list, such as below.
{A: C}
{B: D}
{C: A,D}
{D: C,B,E}
{E: D,F,G}
{F: E}
{G: E}
My problem is: above undirected acyclic grapgh has multi independent source vertexes, which are A and B, and multi independent sink vertexes, which are F and G. How can I turn it to an DAG? The DAG can be expressed by adajacency list below
{A: C}
{B: D}
{C: D}
{D: E}
{E: F, G}
I have an simple solution with normal DFS below. However, is there any more efficiant solution or algorithm?
- For each source vertex, do DFS and will find the only shortest path that lead to the sink vertices.
- Add above path to the final DAG
- Repeat steps 1 and 2 for each source vertex