Simple recursive DFS yet efficient in cpp


  • 0
    class Solution {
    private:
        unordered_map<UndirectedGraphNode*, UndirectedGraphNode*> node_map;
    public:
        UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
            if(!node) return NULL;
            UndirectedGraphNode *cloned_node = new UndirectedGraphNode(node->label);
            node_map[node] = cloned_node;
            for(auto& neighbor: node->neighbors)
            {
                if(node_map.count(neighbor)) cloned_node->neighbors.push_back(node_map[neighbor]);
                else
                {
                    UndirectedGraphNode *cloned_neighbor = cloneGraph(neighbor);
                    cloned_node->neighbors.push_back(cloned_neighbor);
                }
            }
            return cloned_node;
        }
    };

Log in to reply
 

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