思路:
方法一:DFS,要保存一个集合来判断哪些节点已经复制过了,这里使用了unordered_map
来看集合中是否已经有了某个节点(key)。
/**
* Definition for undirected graph.
* struct UndirectedGraphNode {
* int label;
* vector<UndirectedGraphNode *> neighbors;
* UndirectedGraphNode(int x) : label(x) {};
* };
*/
class Solution {
private:
UndirectedGraphNode *clone(UndirectedGraphNode *node, unordered_map<const UndirectedGraphNode *, UndirectedGraphNode *> ©) {
if(copy.find(node) != copy.end()) {
return copy[node];
}
UndirectedGraphNode *new_node = new UndirectedGraphNode(node->label);
copy[node] = new_node;
for(auto nnr : node->neighbors) {
new_node->neighbors.push_back(clone(nnr, copy));
}
return new_node;
}
public:
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
if(node == nullptr) return nullptr;
unordered_map<const UndirectedGraphNode *, UndirectedGraphNode *> copy;
clone(node, copy);
return copy[node];
}
};
方法二:BFS,注意自环的情况。
/**
* 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 == nullptr) return nullptr;
queue<UndirectedGraphNode*> q;
q.push(node);
//judge hashmap
unordered_map<const UndirectedGraphNode *, UndirectedGraphNode *> copy;
UndirectedGraphNode *new_node = new UndirectedGraphNode(node->label);
copy[node] = new_node;
while(!q.empty()) {
const UndirectedGraphNode *cur = q.front();
q.pop();
for(auto nnr : cur->neighbors) {
if(copy.find(nnr) != copy.end()) {
copy[cur]->neighbors.push_back(copy[nnr]);//self-circle
}else {
UndirectedGraphNode *new_node = new UndirectedGraphNode(nnr->label);
copy[nnr] = new_node;
copy[cur]->neighbors.push_back(new_node);
q.push(nnr);
}
}
}
return copy[node];
}
};