-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path0133.cpp
More file actions
27 lines (25 loc) · 753 Bytes
/
Copy path0133.cpp
File metadata and controls
27 lines (25 loc) · 753 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
public:
Node *cloneGraph(Node *node) {
if (!node) return nullptr;
Node *head = new Node(node->val);
unordered_map<Node *, Node *> um({{node, head}});
stack<Node *> st;
st.push(node);
while (!st.empty()) {
Node *node = st.top();
st.pop();
for (Node *c : node->neighbors) {
if (um.find(c) != um.end()) {
um[node]->neighbors.push_back(um[c]);
continue;
}
Node *n = new Node(c->val);
um[node]->neighbors.push_back(n);
um.insert(make_pair(c, n));
st.push(c);
}
}
return head;
}
};