美文网首页
133. Clone Graph

133. Clone Graph

作者: 阿团相信梦想都能实现 | 来源:发表于2016-09-16 06:59 被阅读0次
    traverse graph (Breadth First Search)
    copy using HashMap 
    
    # Definition for a undirected graph node
    # class UndirectedGraphNode(object):
    #     def __init__(self, x):
    #         self.label = x
    #         self.neighbors = []
    
    class Solution(object):
        def cloneGraph(self, node):
            """
            :type node: UndirectedGraphNode
            :rtype: UndirectedGraphNode
            """
            if node is None: 
                return None
            #if graph is not empty, make a copy of the first node 
            cloned_node=UndirectedGraphNode(node.label)
            #create a hashmap with key=node in the original graph,value=cloned node 
            cloned={node:cloned_node}
            #store the next level of nodes to be visited  
            queue=[node]
            
            while queue: 
                current=queue.pop()
                #loop through the neighbours of the current node 
                for neighbor in current.neighbors:
                    #if the neighbor node hasn't been cloned before, make a clone 
                    if neighbor not in cloned: 
                        queue.append(neighbor)
                        cloned_neighbor=UndirectedGraphNode(neighbor.label)
                        cloned[neighbor]=cloned_neighbor
                    #attach the created neighbors to the current graph node 
                    cloned[current].neighbors.append(cloned[neighbor])
            return cloned[node]
                        
    

    相关文章

      网友评论

          本文标题:133. Clone Graph

          本文链接:https://www.haomeiwen.com/subject/hfzbettx.html