133. Clone Graph
1
/ \
/ \
0 --- 2
/ \
\_/Last updated
Was this helpful?
1
/ \
/ \
0 --- 2
/ \
\_/Last updated
Was this helpful?
Was this helpful?
/**
* Definition for undirected graph.
* struct UndirectedGraphNode {
* int label;
* vector<UndirectedGraphNode *> neighbors;
* UndirectedGraphNode(int x) : label(x) {};
* };
*/
class Solution {
// mp maps original node to the copy node
unordered_map <UndirectedGraphNode*, UndirectedGraphNode*> mp;
public:
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
if(!node) return node;
queue<UndirectedGraphNode* > q;
UndirectedGraphNode* head = new UndirectedGraphNode(node->label);
mp[node] = head;
q.push(node);
while(!q.empty()){
// do two things: 1. update mapping record for NEIGH node 2. copy neighbor for the current node
UndirectedGraphNode * cur = q.front(); q.pop();
for(auto neigh : cur->neighbors){
if(mp.find(neigh) == mp.end()){
UndirectedGraphNode* cp_node = new UndirectedGraphNode(neigh->label);
mp[neigh] = cp_node;
q.push(neigh);
}
// copy cur neighbors
mp[cur] -> neighbors.push_back(mp[neigh]);
}
}
return head;
}
};/**
* Definition for undirected graph.
* struct UndirectedGraphNode {
* int label;
* vector<UndirectedGraphNode *> neighbors;
* UndirectedGraphNode(int x) : label(x) {};
* };
*/
class Solution {
unordered_map <UndirectedGraphNode*, UndirectedGraphNode*> mp;
public:
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
if(!node) return node;
if(mp.find(node) == mp.end()){
UndirectedGraphNode * head = new UndirectedGraphNode(node->label);
mp[node] = head;
for(auto neigh: node->neighbors){
mp[node]-> neighbors.push_back(cloneGraph(neigh));
}
}
return mp[node];
}
};