Python DFS recursive solution


  • 0
    G
    class Solution:
        # @param node, a undirected graph node
        # @return a undirected graph node
        def cloneGraph(self, node):
            cloned = {}
            
            def clone(node, cloned=cloned):
                if node is None: return None
                lbl = node.label
                try:
                    return cloned[lbl]
                except:
                    pass
                new_node = UndirectedGraphNode(lbl)
                cloned[lbl] = new_node
                new_node.neighbors = node.neighbors and map(clone, node.neighbors)
                return new_node
            
            return clone(node)
    

Log in to reply
 

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