# EP133 Clone Graph

map<Node, Node> m 的一个map来记住哪些已经拷贝了。

``````/*
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> neighbors;

Node() {}

Node(int _val, vector<Node*> _neighbors) {
val = _val;
neighbors = _neighbors;
}
};
*/
class Solution {
public:
Node* cloneGraph(Node* node) {
if (!node) return nullptr;

Node* copy = new Node(node->val, {});

m[node] = copy;

stack<Node*> s;

s.push(node);

while (!s.empty()) {
Node* tmp = s.top();
s.pop();

for (auto neighbor : tmp->neighbors) {
if (m.find(neighbor) == m.end()) {
s.push(neighbor);
m[neighbor] = new Node(neighbor->val, {});
}
m[tmp]->neighbors.push_back(m[neighbor]);
}
}

return copy;
}

private:

map<Node*, Node*> m;
};
``````

DFS:

``````class Solution {
public:
Node* cloneGraph(Node* node) {
if (!node) {
return NULL;
}
if (copies.find(node) == copies.end()) {
copies[node] = new Node(node -> val, {});
for (Node* neighbor : node -> neighbors) {
copies[node] -> neighbors.push_back(cloneGraph(neighbor));
}
}
return copies[node];
}
private:
unordered_map<Node*, Node*> copies;
};
``````