Tutorialspoint
Problem
Solution
Submissions

Clone a Directed Graph

Certification: Intermediate Level Accuracy: 0% Submissions: 0 Points: 12

Write a C# program to clone a directed graph. The input graph is represented by a list of nodes, where each node contains a value and a list of its neighbors. Return a deep copy (clone) of the graph.

Example 1
  • Input: adjList = [[2,4],[1,3],[2,4],[1,3]]
  • Output: [[2,4],[1,3],[2,4],[1,3]]
  • Explanation:
    • Node 1 has neighbors: Node 2 and Node 4
    • Node 2 has neighbors: Node 1 and Node 3
    • Node 3 has neighbors: Node 2 and Node 4
    • Node 4 has neighbors: Node 1 and Node 3
    • The returned graph has the same structure.
Example 2
  • Input: adjList = [[]]
  • Output: [[]]
  • Explanation:
    • The graph has only one node with no neighbors.
Constraints
  • The number of nodes in the graph is in the range [0, 100]
  • 1 ≤ Node.val ≤ 100
  • Node.val is unique for each node
  • There are no repeated edges and no self-loops in the graph
  • Time Complexity: O(|V| + |E|) where |V| is the number of vertices and |E| is the number of edges
  • Space Complexity: O(|V|) for storing the visited nodes
GraphGooglePhillips
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use depth-first search (DFS) or breadth-first search (BFS) to traverse the graph.
  • Keep a mapping between original nodes and cloned nodes to avoid duplicate cloning.
  • For each original node, create a corresponding clone node if it doesn't exist.
  • For each neighbor of the original node, create a clone if it doesn't exist and add it to the current clone's neighbors.
  • Return the clone of the provided node.

Steps to solve by this approach:

 Step 1: Create a dictionary to map original nodes to their cloned counterparts.
 Step 2: Use DFS or BFS to traverse the original graph.
 Step 3: For each node we visit, check if we've already created a clone for it.
 Step 4: If not, create a new node with the same value as the original.
 Step 5: Store the mapping between the original and clone in the dictionary.
 Step 6: Recursively process all neighbors of the current node.
 Step 7: For each neighbor, get its clone (or create one if it doesn't exist) and add it to the current node's neighbors list.

Submitted Code :