/**
* Definition for undirected graph.
* struct UndirectedGraphNode {
* int label;
* vector<UndirectedGraphNode *> neighbors;
* UndirectedGraphNode(int x) : label(x) {};
* };
*/
class Solution {
public:
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
unordered_map<UndirectedGraphNode *, UndirectedGraphNode *> m;
return getCopyGraph(node, m);
}
private:
UndirectedGraphNode * getCopyGraph(UndirectedGraphNode *node, unordered_map<UndirectedGraphNode *, UndirectedGraphNode *>& m) {
if (!node) {
return NULL;
}
if (m.count(node)) {
return m[node];
}
UndirectedGraphNode * newNode = new UndirectedGraphNode(node->label);
m[node] = newNode;
vector<UndirectedGraphNode *> v;
for (int i = 0; i < node->neighbors.size(); i++) {
v.push_back(getCopyGraph(node->neighbors[i], m));
}
newNode->neighbors = v;
return newNode;
}
};