Simple, Clean C++ solution using BFS


  • 0
    N

    Code is easily understandable. I keep the mapping of original nodes to cloned nodes in a map. This helps to decide whether to create a new node for cloning or it is already created previously.

    class Solution {
    public:
        UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
            if(node == NULL) return NULL;
            unordered_map <UndirectedGraphNode*, UndirectedGraphNode*> mp;
            queue <UndirectedGraphNode*> q;
            q.push(node);
            UndirectedGraphNode* start = new UndirectedGraphNode(node->label);
            mp[node] = start;
            while(! q.empty()){
                UndirectedGraphNode* original = q.front();
                UndirectedGraphNode* duplicate = mp[original];
                q.pop();
                for(int i=0; i< original->neighbors.size(); i++){
                    if(mp.find(original->neighbors[i]) != mp.end()){
                        duplicate->neighbors.push_back(mp[original->neighbors[i]]);
                    }else{
                        UndirectedGraphNode* temp = new UndirectedGraphNode(original->neighbors[i]->label);
                        duplicate->neighbors.push_back(temp);
                        q.push(original->neighbors[i]);
                        mp[original->neighbors[i]] = temp;
                    }
                }
            }
            return start;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.