VOOZH about

URL: https://www.geeksforgeeks.org/dsa/clone-directed-acyclic-graph/

⇱ Clone a Directed Acyclic Graph - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Clone a Directed Acyclic Graph

Last Updated : 23 Jul, 2025

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:

  • Initialize an empty hash map to keep track of the visited nodes and their clones.
  • Perform a DFS traversal of the original graph.
  • For each visited node, create a clone of the node and add it to the hash map.
  • For each outgoing edge of the visited node, check if the destination node is already in the hash map. If it is, add the corresponding clone to the clone of the visited node. If it is not, perform a DFS on the destination node and repeat the previous steps.
  • Once the DFS traversal is complete, return the clone of the starting node.

Implementation:


Output
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

Comment
Article Tags: