Very clean C++ DFS solution, 26ms


  • 0
    T
    class Solution {
    public:
        UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
            if (node == nullptr) {
                return nullptr;
            }
            UndirectedGraphNode* newNode = new UndirectedGraphNode(node->label);
            hash[newNode->label] = newNode;
            for (auto neighbor : node->neighbors) {
                if (hash.find(neighbor->label) != hash.end()) {
                    newNode->neighbors.push_back(hash[neighbor->label]);
                } else {
                    newNode->neighbors.push_back(cloneGraph(neighbor));
                }
            }
            return newNode;
        }
    
    private:
        unordered_map<int, UndirectedGraphNode*> hash;
    };
    

Log in to reply
 

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