Python solution with detailed explanation


  • 0
    G

    Solution

    Clone Graph https://leetcode.com/problems/clone-graph/

    • Simple recursive algorithm to copy with a dictionary
    class Solution:
        def helper(self, node, cache):
            if node is None:
                return None
            elif node in cache:
                return cache[node]
            else:
                cache[node] = UndirectedGraphNode(node.label)
                for x in node.neighbors:
                    cache[node].neighbors.append(self.helper(x, cache))
                return cache[node]
        
        # @param node, a undirected graph node
        # @return a undirected graph node
        def cloneGraph(self, node):
            return self.helper(node, {})
    

Log in to reply
 

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