Instructions
You are given one node of a connected, undirected graph. Return a deep copy of the whole graph.
Each node has a value val and a list neighbors of the nodes it is joined to. The nodes have the values 1 to n, each value used once, and you are given the node with value 1. If the graph is empty, node is null (None in Python) and you return null (None).
A deep copy means:
- every node of the copy is a new node object. Returning any of the original nodes fails the test;
- the copy has the same values and the same edges as the original;
- each copied node keeps its neighbours in the same order as the original node.
Return the copy of node 1.
How the input is shown
The graph is shown as a list of neighbour lists: entry i lists the values of the neighbours of the node with value i + 1. For example, [[2, 3], [1], [1]] means node 1 is joined to nodes 2 and 3. The judge builds the nodes from this list before calling your function, and reads your copy back into the same form. The empty list [] is the empty graph.
Hint: keep a map from each original node to its copy. When you meet a node that is already in the map, use its copy instead of making a new one. This stops the cycles in the graph from making you loop forever.
Examples
Example 1
- Input:
- [[3,2],[1,4],[4,1],[2,3]]
- Output:
- [[3,2],[1,4],[4,1],[2,3]]
Four nodes joined in a square: 1-2, 2-4, 4-3 and 3-1. The copy has the same edges, and node 1 of the copy lists its neighbours as 3 then 2, in the same order as the original.
Example 2
- Input:
- [[]]
- Output:
- [[]]
One node with value 1 and no neighbours. The copy is one new node with value 1 and an empty neighbour list.
Example 3
- Input:
- []
- Output:
- []
The graph is empty, so node is null and the answer is null.
Constraints
0 <= n <= 15(number of nodes)- At most
30edges. - The graph is connected and undirected: if node
alistsb, then nodeblistsa. - No edge joins a node to itself, and no edge appears twice.
3 examples run when you press Run. Submit checks every hidden test too.
- Input:
- [[3,2],[1,4],[4,1],[2,3]]
- Expected:
- [[3,2],[1,4],[4,1],[2,3]]
- Input:
- [[]]
- Expected:
- [[]]
- Input:
- []
- Expected:
- []
Run checks your code against the 3 examples. Submit checks it against all 93 tests and needs a free account. You can also try ideas in the free JavaScript or Python compiler.