Clone Graph
Explore how to clone an undirected graph by creating a deep copy of nodes and their connections. This lesson helps you understand graph traversal, adjacency representation, and ensures the copied graph is independent from the original. You will learn to implement this using C++ and prepare for coding interviews involving graph problems.
We'll cover the following...
Statement
You are given a reference to a single node in an undirected, connected graph. Your task is to create a deep copy of the graph starting from the given node. A deep copy means creating a new instance of every node in the graph with the same data and edges as the original graph, such that changes in the copied graph do not affect the original graph.
Each node in the graph contains two properties:
data: The value of the node, which is the same as its index in the adjacency list.neighbors: A list of connected nodes, representing all the nodes directly linked to this node.
However, in the test cases, a graph is represented as an adjacency list to understand node relationships, where each index in the list represents a node (using 1-based indexing). For example, for
The adjacency list will be converted to a graph at the backend and the first node of the graph will be passed to your code.
Constraints:
Number of nodes Node.dataNode.datais unique for each node.The graph is undirected, i.e., there are no self-loops or repeated edges.
The graph is connected, i.e., any node can be visited from a given node.
Examples
Understand the problem
Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps us to check if you’re solving the correct problem:
Clone Graph
Which graph is made from the given input?
[[2, 5], [1, 3], [2, 4], [3, 5], [1, 4]]
3-------1
| \
| 2
| /
5--------4
1-------5
| \
| 3
| /
2--------4
1-------2
| \
| 3
| /
5--------4
1-------2
| \
| 5
| /
3--------4
Figure it out!
We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.
Try it yourself
Implement your solution in CloneGraph.cpp in the following coding playground.
Node* Clone(Node* root) {// Replace this placeholder return statement with your codereturn root;}