zoukankan      html  css  js  c++  java
  • BFS——克隆图,发现直接copy会出现某些环路的边会丢失,还是要先copy节点,再copy边

    137. 克隆图

    中文
    English

    克隆一张无向图. 无向图的每个节点包含一个 label 和一个列表 neighbors. 保证每个节点的 label 互不相同.

    你的程序需要返回一个经过深度拷贝的新图. 新图和原图具有同样的结构, 并且对新图的任何改动不会对原图造成任何影响.

    样例

    样例1

    输入:
    {1,2,4#2,1,4#4,1,2}
    输出: 
    {1,2,4#2,1,4#4,1,2}
    解释:
    1------2  
          |  
          |  
          |  
          |  
          4   
    

    说明

    关于无向图的表示: http://www.lintcode.com/help/graph/

    注意事项

    你需要返回与给定节点具有相同 label 的那个节点.

    """
    class UndirectedGraphNode:
         def __init__(self, x):
             self.label = x
             self.neighbors = []
    """
    from collections import deque
    
    
    class Solution:
        """
        @param node: A undirected graph node
        @return: A undirected graph node
        """
        def cloneGraph(self, node):
            # write your code here
            if not node:
                return None
            
            def copy_graph_nodes(node):
                nodes = {}
                seen = {node}
                q = deque([node])
                while q:
                    n = q.popleft()
                    new_node = UndirectedGraphNode(n.label)
                    nodes[n] = new_node
                    for neighbor in n.neighbors:
                        if neighbor not in seen:
                            seen.add(neighbor)
                            q.append(neighbor)
                
                return nodes
            
            def build_dir(node, nodes):
                q = deque([node])
                seen = {node}
                while q:
                    n = q.popleft()
                    for neighbor in n.neighbors:
                        nodes[n].neighbors.append(nodes[neighbor])
                        if neighbor not in seen:
                            seen.add(neighbor)
                            q.append(neighbor)
                            
                            
            nodes = copy_graph_nodes(node)
            build_dir(node, nodes)
            
            return nodes[node]
            
    
  • 相关阅读:
    Python3之random模块常用方法
    Go语言学习笔记(九)之数组
    Go语言学习笔记之简单的几个排序
    Go语言学习笔记(八)
    Python3之logging模块
    Go语言学习笔记(六)
    123. Best Time to Buy and Sell Stock III(js)
    122. Best Time to Buy and Sell Stock II(js)
    121. Best Time to Buy and Sell Stock(js)
    120. Triangle(js)
  • 原文地址:https://www.cnblogs.com/bonelee/p/14274945.html
Copyright © 2011-2022 走看看