Simple accepted Python solution

  • 0
    # Definition for a undirected graph node
    # class UndirectedGraphNode:
    #     def __init__(self, x):
    #         self.label = x
    #         self.neighbors = []
    class Solution:
        # @param node, a undirected graph node
        # @return a undirected graph node
        def cloneGraph(self, node):
            if node == None:
                return None
            queue = [node]
            nodeMap = {}
            newNode = UndirectedGraphNode(node.label)
            nodeMap[node.label] = newNode
            while queue:
                curr = queue.pop(0)
                for neighbor in curr.neighbors:
                    if not nodeMap.has_key(neighbor.label):
                        nodeMap[neighbor.label] = UndirectedGraphNode(neighbor.label)
            return newNode

Log in to reply

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