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 的那个节点.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
"""
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 @   bonelee  阅读(96)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」
历史上的今天:
2017-01-13 YCSB benchmark测试cassandra性能——和web服务器测试性能结果类似
2017-01-13 使用cqlsh远程连接cassandra——设置cassandra.yaml里rpc_address和listen_address为ipv4地址即可
2017-01-13 MongoDB架构——记得结合前面的文章看,里面的图画的很好
2017-01-13 ycsb两个阶段说明
2017-01-13 YCSB benchmark测试mongodb性能——和web服务器测试性能结果类似
2017-01-13 MongoDB GridFS——本质上是将一个文件分割为大小为256KB的chunks 每个chunk里会放md5标识 取文件的时候会将这些chunks合并为一个整体返回
2017-01-13 mongodb分片介绍—— 基于范围(数值型)的分片 或者 基于哈希的分片
点击右上角即可分享
微信分享提示