Copy a Network With New Labels

Medium · Graphs, BFS & DFS · about 20 min

A school's computer network is stored as an adjacency list: adj[i] lists the computers directly cabled to computer i. Cables are two-way, so if j is in adj[i] then i is in adj[j].

You are moving the part of the network that computer 0 can reach to a new building, and the new building numbers its computers in a fixed way:

  1. Computer 0 gets the new number 0.
  2. Run a breadth-first search from computer 0. Take computers out of the queue in order, and look at each one's neighbours in the order they are listed. Each neighbour you have never seen gets the next new number (1, 2, 3, ...) and joins the queue.

Return the adjacency list of the copy: entry k lists the new numbers of the neighbours of the computer numbered k, in the same order as in its original list. Computers that 0 cannot reach are not copied. An empty adj gives [].

Example:

copy_from_node_zero([[2], [2], [0, 1]]) → [[1], [0, 2], [1]]

(Old 0 becomes 0, old 2 becomes 1, old 1 becomes 2.)

Hints

  • Keep a map from old number to new number. It also tells you which computers you have already seen.
  • Run the breadth-first search first and only hand out new numbers. Build the copy afterwards.
  • For the computer with new number k, take its old neighbour list and replace every entry with its new number.

Learn the pattern first: the Graphs, BFS & DFS lesson.

More Graphs, BFS & DFS problems