Complete-Preparation

🎉 One-stop destination for all your technical interview Preparation 🎉

View the Project on GitHub

133. Clone Graph 🌟🌟

Given a reference of a node in a connected undirected graph.

Return a deep copy (clone) of the graph.

Each node in the graph contains a value (int) and a list (List[Node]) of its neighbors.

class Node {
    public int val;
    public List<Node> neighbors;
}

Solution

DFS Solution

Code

class Solution {
private:
    Node* dfs(Node* node, unordered_map<Node*, Node*>& copies)
    {
        // base case
        if (node == NULL)
            return NULL;

        // if node is already visited, return the node
        if (copies.find(node) != copies.end())
            return copies[node];

        // else create a new node and add it to the map
        Node* newNode = new Node(node->val);
        copies[node] = newNode;

        // add all the neighbors of the node in the new node
        for (Node* x : node->neighbors) {
            newNode->neighbors.push_back(dfs(x, copies));
        }

        // return new node
        return newNode;
    }

public:
    Node* cloneGraph(Node* node)
    {
        unordered_map<Node*, Node*> copies;
        return dfs(node, copies);
    }
};

BFS Solution

Code

class Solution {
public:
    Node* cloneGraph(Node* node)
    {
        if (node == NULL)
            return NULL;

        // create a map to store the cloned nodes & queue for bfs
        unordered_map<Node*, Node*> copies;
        queue<Node*> q;
        q.push(node);

        // create a new node with the same value as the original node
        // and add it to the map
        Node* newNode = new Node(node->val);
        copies[node] = newNode;

        // bfs
        while (!q.empty()) {
            Node* frontNode = q.front();
            q.pop();

            // add all the neighbors of the node in the new node
            for (Node* x : frontNode->neighbors) {
                if (copies.find(x) == copies.end()) { // if x is not in the map
                    copies[x] = new Node(x->val); // add x->val in the map
                    q.push(x); // add x to the queue
                }
                // add x to the neighbors of the cloned node
                copies[frontNode]->neighbors.push_back(copies[x]);
            }
        }
        return newNode;
    }
};