30 Day Challenge Day 17 | Leetcode 133. Clone Graph
题解
Medium
BFS
Deep Copy 的一个例子。
class Solution {
public:
Node* cloneGraph(Node* node) {
if(!node) return nullptr;
unordered_map<Node*, Node*> m;
Node* copy = new Node(node->val);
m[node] = copy;
queue<Node*> q;
q.push(node);
while(!q.empty()) {
Node* t = q.front();
q.pop();
for(auto n : t->neighbors) {
if(!m.count(n)) {
m[n] = new Node(n->val);
q.push(n);
}
m[t]->neighbors.push_back(m[n]);
}
}
return copy;
}
};