菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
280
0

BFS——克隆图,发现直接copy会出现某些环路的边会丢失,还是要先copy节点,再copy边

原创
05/13 14:22
阅读数 56032

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]
        

 

发表评论

0/200
280 点赞
0 评论
收藏