Make an Independent Copy of a Connected Network
Implement cloneGraph
You are given one node of a connected, undirected graph; every node has an integer value and a list of the nodes it is connected to. Return a deep copy of the graph: brand-new nodes with the same values and the same neighbours (in the same order), sharing no node with the original. For practice, graphs are written as adjacency lists (row i lists the values of the neighbours of node i + 1).
A graph can contain cycles, so simply following neighbours would never end. Remember which originals already have a copy — a dictionary from original to copy — so every node is copied exactly once.
Example 1:
Input: graph = [[2,3],[1,4],[1,4],[2,3,5],[4]]
Output: [[2,3],[1,4],[1,4],[2,3,5],[4]]
Example 2:
Input: graph = [[]]
Output: [[]]
Example 3:
Input: graph = []
Output: []
+ 12 hidden test cases run on Submit.
Constraints:
- ●
0 ≤ number of nodes ≤ 100. The graph is undirected and CONNECTED; node values are 1, 2, …, n. You receive the node with value 1 (or null for an empty graph); each node has an integer val and a list neighbors of the nodes it is connected to - ●
For testing, a graph is described by an adjacency list: row i (0-based) lists the values of the neighbours of the node with value i + 1, in the order they appear in that node's neighbors list. Example: [[2,3],[1],[1]] is a path 2 – 1 – 3 - ●
Return a deep copy: a graph of brand-new nodes with the same values and, at every node, the same neighbours in the same order. The copy may not share any node object with the original graph - ●
The returned graph is printed as its adjacency list; a copy that reuses an original node is rejected
graph =