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]
        

 

posted @ 2021-01-13 23:03  bonelee  阅读(96)  评论(0编辑  收藏  举报