leetcode

Solution to some Leetcode problems written in C++
git clone git://git.dimitrijedobrota.com/leetcode.git
Log | Files | Refs | README | LICENSE

0133.cpp (753B)


      1 class Solution {
      2   public:
      3     Node *cloneGraph(Node *node) {
      4         if (!node) return nullptr;
      5 
      6         Node *head = new Node(node->val);
      7         unordered_map<Node *, Node *> um({{node, head}});
      8 
      9         stack<Node *> st;
     10         st.push(node);
     11         while (!st.empty()) {
     12             Node *node = st.top();
     13             st.pop();
     14             for (Node *c : node->neighbors) {
     15                 if (um.find(c) != um.end()) {
     16                     um[node]->neighbors.push_back(um[c]);
     17                     continue;
     18                 }
     19                 Node *n = new Node(c->val);
     20                 um[node]->neighbors.push_back(n);
     21                 um.insert(make_pair(c, n));
     22                 st.push(c);
     23             }
     24         }
     25         return head;
     26     }
     27 };