Elegant Python DFS code. Remember the neighbors list has to be exactly the same!

  • 0
    class Solution:
        # @param node, a undirected graph node
        # @return a undirected graph node
        def cloneGraph(self, start):
            NodeClass = UndirectedGraphNode
            if not start:
                return None
                dummy = []
                mapping = {}
                stack = [(start, dummy)]
                while stack:
                    old_node, siblings = stack.pop()
                    if old_node not in mapping:
                        new_node = NodeClass(old_node.label)
                        mapping[old_node] = new_node
                        for x in old_node.neighbors[::-1]:  # reversed order otherwise
                            stack.append((x, new_node.neighbors))
                return dummy[0] if dummy else None

Log in to reply

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