Clone Graph
mediumGraphs+20 XPTime limit 2s
A connected undirected graph has nodes 1 … n; each node knows its list of neighbours. Make a deep copy of the graph — new node objects whose neighbour lists point to the new nodes — starting from node 1.
To show that your copy is complete and correctly wired, walk your copy with BFS from node 1 and print every node as you take it out of the queue, together with its neighbour list.
Input:
- line 1:
n - next
nlines: lineidescribes nodei: first the number of neighboursd, then thedneighbours in their stored order
Output: n lines in BFS order: v: a b c — the node's value, a colon, then its neighbours in their stored order (just v: if it has none). In BFS, enqueue unvisited neighbours in the stored order.
Constraints: 1 ≤ n ≤ 10⁴, total neighbour entries ≤ 6·10⁴, no self-loops or repeated edges, the graph is connected.
The technique: BFS (or DFS) over the original with a hash map original → copy. When you meet a node for the first time, create its copy; then append the copied neighbour to the current copy's list.
Sample input 1
4 2 2 4 2 1 3 2 2 4 2 1 3
Sample output 1
1: 2 4 2: 1 3 4: 1 3 3: 2 4
Sample input 2
1 0
Sample output 2
1:
📖 Stuck? Learn the pattern
Read input from standard input and print the answer to standard output. Your code runs in a secure sandbox against the samples (Run) and hidden tests (Submit).