This is a simple question. Just use a map to log whether the node was copied. I made a mistake by putting hash.emplace(node, clonedNode); after the for loop, this will cause infinite loop.
/**
* 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<UndirectedGraphNode *, UndirectedGraphNode *> hash;
if(node == NULL) {
return NULL;
}
return cloneGraphHelper(node, hash);
}
UndirectedGraphNode * cloneGraphHelper(UndirectedGraphNode *node, unordered_map<UndirectedGraphNode *, UndirectedGraphNode *>& hash) {
if(hash.count(node) > 0) {
return hash[node];
}
UndirectedGraphNode * clonedNode = new UndirectedGraphNode(node->label);
hash.emplace(node, clonedNode); // made mistake here
vector<UndirectedGraphNode *> neighbors;
for(UndirectedGraphNode * neighbor : node->neighbors) {
UndirectedGraphNode * cloneNeighbor = cloneGraphHelper(neighbor, hash);
neighbors.emplace_back(cloneNeighbor);
}
swap(clonedNode->neighbors,neighbors);
return clonedNode;
}
};
Slightly modifid
/**
* 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 == NULL) {
return NULL;
}
unordered_map<UndirectedGraphNode *, UndirectedGraphNode *> hash;
return cloneGraph(node, hash);
}
UndirectedGraphNode * cloneGraph(UndirectedGraphNode* node, unordered_map<UndirectedGraphNode *, UndirectedGraphNode *>& hash) {
if(hash.count(node) > 0) {
return hash[node];
}
UndirectedGraphNode * cloneNode = new UndirectedGraphNode(node->label);
hash.emplace(node, cloneNode);
for(UndirectedGraphNode * neighbor : node->neighbors) {
cloneNode->neighbors.emplace_back(cloneGraph(neighbor, hash));
}
return cloneNode;
}
};
No comments:
Post a Comment