Clone Graph 07/30

Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors.

How we serialize an undirected graph:

Nodes are labeled uniquely.

We use # as a separator for each node, and , as a separator for node label and each neighbor of the node.

As an example, consider the serialized graph {0,1,2#1,2#2,2}.

The graph has a total of three nodes, and therefore contains three parts as separated by #.

  1. First node is labeled as 0. Connect node 0 to both nodes 1 and 2.

  2. Second node is labeled as 1. Connect node 1 to node 2.

  3. Third node is labeled as 2. Connect node 2 to node 2 (itself), thus forming a self-cycle.

Visually, the graph looks like the following:

   1
  / \
 /   \
0 --- 2
     / \
     \_/

Have you met this question in a real interview? Yes

Example

return a deep copied graph.

先把图里的所有node,用宽度有限搜索存起来,然后用hashmap建立旧node和新node的一一对应,然后遍历每一个node的邻居,根据这个邻居,来找到对应的信建立的node,也就是map的value,然后把找到的对应的旧邻居的新邻居,加到对应的点的邻居队列里

Last updated