Clone Graph
Try to solve the Clone Graph problem.
We'll cover the following
Statement
Given a reference of a node in a graph with data and a list of neighbors, create a deep copy of the graph. The graph has the following properties:
-
Undirected: The edges of the graph are bidirectional.
-
Connected: A path will always exist between any two nodes.
In a deep copy, a new instance of every node is created with the same data as in the original graph. Any modifications made to the new graph are not reflected in the original graph.
For simplicity, we are creating a graph using an adjacency list, where the data of each node is represented by its index in the adjacency list. Each list in the adjacency list describes the set of neighbors of a node in the graph. The index in the adjacency list starts from 1. For example, for [[2, 3], [1, 3], [1, 2]], there are three nodes in the graph:
node (data = 1): Neighbors are node (data = 2) and node (data = 3).
node (data = 2): Neighbors are node (data = 1) and node (data = 3).
node (data = 3): Neighbors are node (data = 1) and node (data = 2).
Constraints:
- Number of nodes
-
Node.data
Node.data
is 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
Create a free account to view this lesson.
Continue your learning journey with a 14-day free trial.
By signing up, you agree to Educative's Terms of Service and Privacy Policy