Clone Graph
MediumP2Coding
The original problem asks you to deep-copy a connected undirected graph given as node objects. The test harness cannot build node objects, so here the graph is given as an adjacency list.
Nodes are labelled 1..n, and adj[i] lists the neighbours of node i + 1, in a fixed order. Build node objects (each with a value and a list of neighbour nodes) from adj, deep-copy the graph starting from node 1 so that no copied node is shared with the original, then read the copy back and return its adjacency list in the same format and neighbour order. An empty adj returns [].
The graph is connected, so a copy from node 1 reaches every node.
Example 1
- Input
- adj = [[2,4],[1,3],[2,4],[1,3]]
- Output
- [[2,4],[1,3],[2,4],[1,3]]
- Why
- A square: 1-2, 2-3, 3-4, 4-1.
Example 2
- Input
- adj = [[]]
- Output
- [[]]
- Why
- A single node with no neighbours.
Constraints
- 0 <= n <= 100
- adj[i] contains labels in 1..n, no self loops or repeated edges
- The graph is connected.
Hints
Give it a real attempt first. Run shows which examples fail.
Saved automatically
Run checks the 3 visible tests, Submit all 9. ⌘Enter runs, ⌘⇧Enter submits.