Note:
说的复杂,起始就是给整个图复制一下就行了,不能直接返回原来的图
先创建一遍所有的节点,然后【原来的节点,新的节点】这种样子放到hash里面
然后遍历所有的节点,再把所有的边复制一下
随便返回一个节点就可
代码如下:
/*
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> neighbors;
Node() {
val = 0;
neighbors = vector<Node*>();
}
Node(int _val) {
val = _val;
neighbors = vector<Node*>();
}
Node(int _val, vector<Node*> _neighbors) {
val = _val;
neighbors = _neighbors;
}
};
*/
class Solution {
public:
unordered_map<Node*, Node*> hash;
void dfs(Node* node){
hash[node] = new Node(node -> val);
for(auto ver : node -> neighbors)
if(hash.count(ver) == 0)
dfs(ver);
}
Node* cloneGraph(Node* node) {
if(!node) return NULL;
dfs(node);
for(auto[s, e] : hash){
for(int i = 0; i < s -> neighbors.size(); i ++)
e -> neighbors.push_back(hash[s -> neighbors[i]]);
}
return hash[node];
}
};