您的位置:首页 > 其它

leetcode 133: Clone Graph

2015-08-17 22:13 585 查看
Not a hard problem, just the details are a little tricky to think. I used the queue to BFS, while doing it, I used the unordered set and unordered map to save the nodes that are already been created. Whenever a node is created before, you shouldn't create
a new one with the same label.

/**
* 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)
return NULL;
queue<UndirectedGraphNode*> qold;//queue for the original graph
queue<UndirectedGraphNode*> qnew;//queue for the new graph
unordered_set<UndirectedGraphNode*> oldset;//save all nodes that are existed
unordered_map<int,UndirectedGraphNode*> newset;
qold.push(node);
UndirectedGraphNode* pbegin=new UndirectedGraphNode(node->label);
qnew.push(pbegin);
while(!qold.empty())
{
UndirectedGraphNode* pold=qold.front();
qold.pop();
UndirectedGraphNode* pnew=qnew.front();
qnew.pop();
if(oldset.find(pold)==oldset.end())//make this node existed if not
{
oldset.insert(pold);
newset.insert(make_pair(pnew->label,pnew));
}
for(int i=0;i<pold->neighbors.size();i++)
{
if(oldset.find(pold->neighbors[i])!=oldset.end())//the neighbor i is an existed node
{
UndirectedGraphNode* ptemp=newset[pold->neighbors[i]->label];//find the existed node's address through label
pnew->neighbors.push_back(ptemp);
}
else
{
UndirectedGraphNode* ptemp=new UndirectedGraphNode(pold->neighbors[i]->label);
pnew->neighbors.push_back(ptemp);
qold.push(pold->neighbors[i]);
qnew.push(ptemp);
oldset.insert(pold->neighbors[i]);
newset.insert(make_pair(pold->neighbors[i]->label,ptemp));
}
}
}
return pbegin;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: