LintCode 137 克隆图(Clone Graph) Python题解

 描述

 Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors. Nodes are labeled uniquely.

You need to return a deep copied graph, which has the same structure as the original graph, and any changes to the new graph will not have any effect on the original graph.

 

You need return the node with the same label as the input node.

 

说明

How we serialize an undirected graph: http://www.lintcode.com/help/graph/

样例

Example1

Input:
{1,2,4#2,1,4#4,1,2}
Output: 
{1,2,4#2,1,4#4,1,2}
Explanation:
1------2  
 \     |  
  \    |  
   \   |  
    \  |  
      4   

 

同时,类的定义是:

"""
class UndirectedGraphNode:
     def __init__(self, x):
         self.label = x
         self.neighbors = []
"""

 

Note: 实话说,第一次遇到类似的题目。复制Python的list和dict等时,a=[1,2,3]; b= a; b.append(4); 的时候,a和b都为[1,2,3,4]。这就是浅复制。要想在数据结构上实现深复制,需要把数据结构的各个部分单独复制。本题中,需要把label和neighbor分别复制。

(本题解参考九章)

# 本参考程序来自九章算法,由 @令狐冲 提供。版权所有,转发请注明出处。
# - 九章算法致力于帮助更多中国人找到好的工作,教师团队均来自硅谷和国内的一线大公司在职工程师。
# - 现有的面试培训课程包括:九章算法班,系统设计班,算法强化班,Java入门与基础算法班,Android 项目实战班,
# - Big Data 项目实战班,算法面试高频题班, 动态规划专题班
# - 更多详情请见官方网站:http://www.jiuzhang.com/?source=code
from collections import deque

"""
class UndirectedGraphNode:
     def __init__(self, x):
         self.label = x
         self.neighbors = []
"""

class Solution:
    """
    @param node: A undirected graph node
    @return: A undirected graph node
    """
    def cloneGraph(self, node):
        root = node #哪个点是入口,待会仍然从这个点开始
        if node is None:
            return node
        # write your code here
        nodes = self.getnodes(node)
        mapping = {}
        for node in nodes:
            mapping[node] = UndirectedGraphNode(node.label)
        
        for node in nodes:
            #new_node = mapping[node]
            for neighbor in node.neighbors:
                #new_neighbor = mapping[neighbor]
                #new_node.neighbors.append(new_neighbor)
                mapping[node].neighbors.append(mapping[neighbor])
                
        return mapping[root]
        
        
    def getnodes(self,node):
        queue = deque([node])
        result = set([node])
        while(queue):
            head = queue.popleft()
            for neighbor in head.neighbors:
                if(neighbor not in result):
                    result.add(neighbor)
                    queue.append(neighbor)
        return result
                
        
        

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值