![]() |
VOOZH | about |
A directed acyclic graph (DAG) is a graph which doesn't contain a cycle and has directed edges. We are given a DAG, we need to clone it, i.e., create another graph that has copy of its vertices and edges connecting them.
Examples:
Input : 0 - - - > 1 - - - -> 4 | / \ ^ | / \ | | / \ | | / \ | | / \ | | / \ | v v v | 2 - - - - - - - - -> 3 Output : Printing the output of the cloned graph gives: 0-1 1-2 2-3 3-4 1-3 1-4 0-2
To clone a DAG without storing the graph itself within a hash (or dictionary in Python). To clone, it we basically do a depth-first traversal of the nodes, taking original node's value and initializing new neighboring nodes with the same value, recursively doing, till the original graph is fully traversed. Below is the recursive approach to cloning a DAG (in Python). We make use of dynamic lists in Python, append operation to this list happens in constant time, hence, fast and efficient initialization of the graph.
Approach:
Implementation:
Graph Before Cloning:- edge 0x1017e70-0x1017ea0:0-1 edge 0x1017ea0-0x1017ed0:1-2 edge 0x1017ed0-0x1017f00:2-3 edge 0x1017f00-0x1017f30:3-4 edge 0x1017ea0-0x1017f00:1-3 edge 0x1017ea0-0x1017f30:1-4 edge 0x1017e70-0x1017ed0:0-2 Graph Before Starts:- Cloning Process Completes. Graph After Cloning:- edge 0x1019020-0x1019050:0-1 edge 0x1019050-0x10190a0:1-2 edge 0x10190a0-0x10190f0:2-3 edge 0x10190f0-0x1019140:3-4 edge 0x1019050-0x1019190:1-3 edge 0x1019050-0x10191e0:1-4 edge 0x1019020-0x1019240:0-2
Creating the DAG by appending adjacent edges to the vertex happens in O(1) time. Cloning of the graph takes O(E+V) time.
Time Complexity : O(V+E)
Space Complexity : O(V+E)
Related Article: Clone an Undirected Graph