[Python] Short solution with Recursion DFS and Hash tables


  • 0
    H

    With a global variable closed list.

    map = {}
    map[None] = None
    
    class Solution:
        # @param node, a undirected graph node
        # @return a undirected graph node
        def cloneGraph(self, node):
            if not node:
                return None
            head = UndirectedGraphNode(node.label)
            map[node] = head
            for n in node.neighbors:
                if n in map:
                    head.neighbors.append(map[n])
                else:
                    neigh = self.cloneGraph(n)
                    head.neighbors.append(neigh)
            return head

Log in to reply
 

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