leetcode - Clone Graph
2013-12-16 09:01 张汉生 阅读(232) 评论(0) 编辑 收藏 举报
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 UndirectedGraphNode * cloneGraph(UndirectedGraphNode *node, unordered_map<int, UndirectedGraphNode*> & curNodes){ 12 UndirectedGraphNode * root = new UndirectedGraphNode(node->label); 13 curNodes[root->label] = root; 14 vector<UndirectedGraphNode*>::iterator itr; 15 for (itr = node->neighbors.begin(); itr!=node->neighbors.end(); itr++){ 16 unordered_map<int,UndirectedGraphNode*>::const_iterator got = curNodes.find ((*itr)->label); 17 if (got==curNodes.end()) 18 root->neighbors.push_back(cloneGraph(*itr, curNodes)); 19 else root->neighbors.push_back(got->second); 20 } 21 return root; 22 } 23 UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) { 24 if (node==NULL) 25 return node; 26 unordered_map<int, UndirectedGraphNode *> curNodes; 27 return cloneGraph(node,curNodes); 28 } 29 };