Solution


  • 0
    K
    /**
     * Definition for undirected graph.
     * struct UndirectedGraphNode {
     *     int label;
     *     vector<UndirectedGraphNode *> neighbors;
     *     UndirectedGraphNode(int x) : label(x) {};
     * };
     */
    class Solution {
        unordered_map<int, UndirectedGraphNode*> visited;
        UndirectedGraphNode* cloneInternal(UndirectedGraphNode* node) {
            if (visited.find(node->label) != visited.end()) {
                return visited[node->label];
            }
            visited[node->label] = new UndirectedGraphNode(node->label);
            for (const auto n : node->neighbors) {
                visited[node->label]->neighbors.push_back(cloneInternal(n));
            }
            return visited[node->label];
        }
    public:
        UndirectedGraphNode* cloneGraph(UndirectedGraphNode* node) {
            if (!node) {
                return node;
            }
            return cloneInternal(node);
        }
    };
    

Log in to reply
 

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