clean C++ DFS solution beats 97%


  • 0
    X
    class Solution {
    public:
        UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
            unordered_map<int, UndirectedGraphNode*> newed;
            return dfs(node, newed);
        }
        UndirectedGraphNode *dfs(UndirectedGraphNode *node, unordered_map<int, UndirectedGraphNode*>& newed) {
            if (!node) return node;
            UndirectedGraphNode *new_node = new UndirectedGraphNode(node->label);
            newed[new_node->label] = new_node;
            for (auto n: node->neighbors) {
                auto it = newed.find(n->label);
                if (it == newed.end()) {
                    new_node->neighbors.push_back(dfs(n, newed));
                } else {
                    new_node->neighbors.push_back(it->second);
                }
            }
            
            return new_node;
        }
    };
    

Log in to reply
 

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