Posted on

Description

Submission

/*
// Definition for a Node.
class Node {
public:
    int val;
    vector<Node*> neighbors;
    
    Node() {
        val = 0;
        neighbors = vector<Node*>();
    }
    
    Node(int _val) {
        val = _val;
        neighbors = vector<Node*>();
    }
    
    Node(int _val, vector<Node*> _neighbors) {
        val = _val;
        neighbors = _neighbors;
    }
};
*/

class Solution {
    unordered_map<Node*, Node*> Map; 
public:
    Node* cloneGraph(Node* node) {
        if(node == NULL) return NULL;
        
        if(Map.find(node) != Map.end()) {
            return Map[node];
        }
        
        Node* newNode = new Node(node->val);
        Map[node] = newNode; 
        
        for(int i = 0; i < node->neighbors.size(); ++i) {
            newNode->neighbors.push_back(cloneGraph(node->neighbors[i]));
        }
        
        return newNode;
    }
};

Leave a Reply

Your email address will not be published. Required fields are marked *