# [leetcode] 133.Clone Graph

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

OJ’s undirected graph serialization:
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
/ \
\_/


/**
* Definition for undirected graph.
* struct UndirectedGraphNode {
*     int label;
*     vector<UndirectedGraphNode *> neighbors;
*     UndirectedGraphNode(int x) : label(x) {};
* };
*/
class Solution {
public:
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
if(node == NULL)return NULL;
UndirectedGraphNode *root = NULL;
cloneGraphRecur(root, node);
return root;
}
void cloneGraphRecur(UndirectedGraphNode *&root, UndirectedGraphNode *&node) {
root = new UndirectedGraphNode(node->label);
existNodes[node->label] = root;
for(auto neighbor:node->neighbors) {
if(existNodes.find(neighbor->label) == existNodes.end()){
UndirectedGraphNode *temp = NULL;
cloneGraphRecur(temp, neighbor);
root->neighbors.push_back(temp);
}
else root->neighbors.push_back(existNodes[neighbor->label]);
}
}
private:
unordered_map<int,UndirectedGraphNode*> existNodes;
};

#### [leetcode] 133. Clone Graph 解题报告

2016-03-05 04:47:30

#### 133. Clone Graph 图的复制，运用了BFS

2016-07-14 20:47:29

#### LeetCode——133.Clone Graph && 621.Task Scheduler

2017-06-25 15:52:32

#### Clone Graph -- LeetCode

2014-04-01 09:53:23

#### [LeetCode][Java] Clone Graph

2015-08-01 17:20:50

#### [leetcode-133]Clone Graph（java）

2015-08-14 21:30:53

#### [C++]LeetCode: 129 Clone Graph (图的深拷贝 BFS && DFS)

2015-01-28 16:52:54

#### LeetCode | Clone Graph

2014-01-03 22:42:29

#### Clone Graph 图的复制 @LeetCode

2013-12-23 05:52:36

#### 【LeetCode】Clone Graph 解题报告

2014-09-11 21:08:40