Clone Graph

update Jul 17, 2017 23:09

lintcodearrow-up-right LeetCodearrow-up-right

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 #.

 First node is labeled as 0. Connect node 0 to both nodes 1 and 2.
 Second node is labeled as 1. Connect node 1 to node 2.
 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.

Basic Idea:

题目所提供的只有一个node,显然要copy整个graph,我们需要先获得所有的node。比较正常的思路是先通过一个BFS获得所有的node,然后进行copy。

具体到如何进行copy,我们可以先尽力一个hashmap<oldNode, newNode>,然后遍历每个oldNode的neighbors,把每个neighbors中的oldNode对应的newNode加入对应newNode的neighbors中。

详见Code。

Python Code:

Java Code:

update 2018-05-18 17:25:32

C++ Code:

在这个实现中,hashmap是 unordered_map<UndirectedGraphNode*, UndirectedGraphNode*>, 相当于和 Java 中 HashMap 存储没有自定义hash的class object时的方法一样,都是用地址作为key,可以保证唯一性。

update 2018-06-17 22:55:34

Update C++

之前的c++解法直接将指针作为key,这里提供一个用label作为key的。