10 lines c++ 72 ms DFS beats 95.79% super easy to understand


  • 0
    T
    std::unordered_map<UndirectedGraphNode *, UndirectedGraphNode *> mymap;
    
    UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
        if(node == NULL) return NULL;
        
        auto it = mymap.find(node);
        if(it!= mymap.end()) return it->second;
    
        UndirectedGraphNode * G = new UndirectedGraphNode(node->label);
        mymap.insert({node, G});
        
        for(auto& it_vec: node->neighbors)
            G->neighbors.push_back(cloneGraph(it_vec));
    
        return G;
    }

Log in to reply
 

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