Clone Graph
Try to solve the Clone Graph problem.
We'll cover the following
Statement#
Given a graph that has nodes 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.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#
1 of 3
2 of 3
3 of 3
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 adjacency list?
[[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 clone_graph.py in the following coding playground. We have provided a useful code template in the other file that you may build on to solve this problem.
Graphs: Introduction
Solution: Clone Graph