VOOZH about

URL: https://www.geeksforgeeks.org/dsa/clone-an-undirected-graph/

⇱ Clone an Undirected Graph - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Clone an Undirected Graph

Last Updated : 13 Apr, 2025

Given a connected undirected graph represented by adjacency list, adjList[][] with nodes and m edges, with each node having a distinct label from 0 to n-1, and each adj[i] represents the list of vertices connected to vertex i.

Create a clone of the graph, where each node in the graph contains an integer val and an array (neighbors) of nodes, containing nodes that are adjacent to the current node.

class Node {
val: integer
neighbors: List[Node]
}

Your task is to clone the given graph and return a reference to the cloned graph.

Note: If you return a correct copy of the given graph, the output will be true; otherwise, if the copy is incorrect, it will print false.

Examples

Input: n = 4, adjList[][] = [[1, 2], [0, 2], [0, 1, 3], [2]]
Output: true
Explanation:
👁 Image

Since the cloned graph is identical to the original, the output will be true.

Input: n = 3, adjList[][] = [[1, 2], [0], [0]]
Output: true
Explanation:
👁 Image
Since the cloned graph is identical to the original, the output will be true.

Why we need to track of the visited/cloned nodes?

We need to track visited or cloned nodes to avoid infinite recursion and redundant work when cloning a graph. Since graphs can contain cycles (where a node can point back to a previously visited node), without keeping track of the nodes we've already cloned, the cloning function would endlessly revisit the same nodes, resulting in a stack overflow or incorrect duplication.

How to keep track of the visited/cloned nodes?

A HashMap/Map is required in order to maintain all the nodes which have already been created. Key stores: Reference/Address of original Node Value stores: Reference/Address of cloned Node A copy of all the graph nodes has been made.

How to connect clone nodes?

While visiting the neighboring vertices of a node uget the corresponding cloned node for u, let’s call that U, now visit all the neighboring nodes for u and for each neighbor find the corresponding clone node(if not found create one) and then push into the neighboring vector of U node. 

How to verify if the cloned graph is a correct?

Perform a BFS traversal on the original graph before cloning, and then again on the cloned graph after cloning is complete. During each traversal, print the value of each node along with its address (or reference). To verify the correctness of the cloning, compare the order of nodes visited in both traversals. If the node values appear in the same order but their addresses (or references) differ, it confirms that the graph has been successfully and correctly cloned.

Explore how to clone an undirected graph, including graphs with multiple connected components, using BFS or DFS to ensure a complete deep copy of all nodes and edges.

[Approach 1] Using BFS traversal - O(V+E) Time and O(V) Space

In the BFS approach, the graph is cloned iteratively using a queue. We begin by cloning the initial node and placing it in the queue. As we process each node from the queue, we visit its neighbors. If a neighbor has not been cloned yet, we create a clone, store it in a map, and enqueue it for later processing. We then add the clone of the neighbor to the current node’s clone’s list of neighbors. This process continues level by level, ensuring that all nodes are visited in breadth-first order. BFS is particularly useful for avoiding deep recursion and handling large or wide graphs efficiently.


Output
true

[Approach 2] Using DFS traversal - O(V+E) Time and O(V) Space

In the DFS approach, the graph is cloned using recursion. We start from the given node and explore as far as possible along each branch before backtracking. A map (or dictionary) is used to keep track of already cloned nodes to avoid processing the same node multiple times and to handle cycles. When we encounter a node for the first time, we create a clone of it and store it in the map. Then, for each neighbor of that node, we recursively clone it and add the cloned neighbor to the current node’s clone. This ensures that all nodes are visited deeply before returning, and the graph structure is faithfully copied.


Output
true


Comment
Article Tags: