My C++ solution. Fairly easy to understand


  • -2
    S

    class Solution {
    public:
    unordered_map <int, UndirectedGraphNode *> visited;
    UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
    if(node == NULL) { return NULL; }
    if(visited.count(node->label) != 0) { return node; }
    UndirectedGraphNode *t = new UndirectedGraphNode(node->label);
    visited[(node->label)] = t;
    int i, size = node->neighbors.size();
    for(i=0;i<size;i++){
    if( visited.count((node->neighbors[i])->label) == 0)
    { t->neighbors.push_back(cloneGraph(node->neighbors[i])); }
    else
    { t->neighbors.push_back( visited[((node->neighbors[i])->label)]); }
    }
    return t;
    }
    };


Log in to reply
 

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