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


  • 0
    B
    class Solution:
        # @param node, a undirected graph node
        # @return a undirected graph node
        def cloneGraph(self, start):
            NodeClass = UndirectedGraphNode
            if not start:
                return None
            else:
                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))
                    siblings.append(mapping[old_node])
                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.