leetcodeSolution to some Leetcode problems written in C++ |
git clone git://git.dimitrijedobrota.com/leetcode.git |
Log | Files | Refs | README | LICENSE |
0133.cpp (753B)
0 class Solution {
1 public:
2 Node *cloneGraph(Node *node) {
3 if (!node) return nullptr;
5 Node *head = new Node(node->val);
6 unordered_map<Node *, Node *> um({{node, head}});
8 stack<Node *> st;
9 st.push(node);
10 while (!st.empty()) {
11 Node *node = st.top();
12 st.pop();
13 for (Node *c : node->neighbors) {
14 if (um.find(c) != um.end()) {
15 um[node]->neighbors.push_back(um[c]);
16 continue;
17 }
18 Node *n = new Node(c->val);
19 um[node]->neighbors.push_back(n);
20 um.insert(make_pair(c, n));
21 st.push(c);
22 }
23 }
24 return head;
25 }
26 };