您的位置:首页 > 其它

leetcode - Clone Graph

2013-12-16 09:01 288 查看
/**
* 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<int, UndirectedGraphNode*> & curNodes){
UndirectedGraphNode * root = new UndirectedGraphNode(node->label);
curNodes[root->label] = root;
vector<UndirectedGraphNode*>::iterator itr;
for (itr = node->neighbors.begin(); itr!=node->neighbors.end(); itr++){
unordered_map<int,UndirectedGraphNode*>::const_iterator got = curNodes.find ((*itr)->label);
if (got==curNodes.end())
root->neighbors.push_back(cloneGraph(*itr, curNodes));
else root->neighbors.push_back(got->second);
}
return root;
}
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
if (node==NULL)
return node;
unordered_map<int, UndirectedGraphNode *> curNodes;
return cloneGraph(node,curNodes);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: