1 /** 2 * Definition for undirected graph. 3 * struct UndirectedGraphNode { 4 * int label; 5 * vector<UndirectedGraphNode *> neighbors; 6 * UndirectedGraphNode(int x) : label(x) {}; 7 * }; 8 */ 9 class Solution { 10 public: 11 12 UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node, unordered_map<UndirectedGraphNode *, UndirectedGraphNode*> &dict) { 13 if (node == NULL) return NULL; 14 UndirectedGraphNode *result = new UndirectedGraphNode(node->label); 15 dict[node] = result; 16 17 for (int i = 0; i < node->neighbors.size(); i++){ 18 19 if (dict.find(node->neighbors[i]) == dict.end()) { 20 21 UndirectedGraphNode *tmp = cloneGraph(node->neighbors[i], dict); 22 result->neighbors.push_back(tmp); 23 } 24 else result->neighbors.push_back(dict[node->neighbors[i]]); 25 } 26 return result; 27 } 28 29 UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) { 30 31 if (node == NULL) return NULL; 32 unordered_map<UndirectedGraphNode *, UndirectedGraphNode *> dict; 33 return cloneGraph(node, dict); 34 } 35 };