LintCode 137 Clone Graph Python problem solution

 describe

 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.

 

illustrate

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

Sample

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   

 

Meanwhile, the class definition is:

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

 

Note:  To be honest, this is the first time I encountered a similar question. When copying Python's list and dict, etc., a=[1,2,3]; b= a; b.append(4);, both a and b are [1,2,3,4]. This is shallow copy. To implement deep copying on a data structure, each part of the data structure needs to be copied separately. In this question, you need to copy the label and neighbor separately.

(Refer to Chapter 9 for the solution to this question)

# 本参考程序来自九章算法,由 @令狐冲 提供。版权所有,转发请注明出处。
# - 九章算法致力于帮助更多中国人找到好的工作,教师团队均来自硅谷和国内的一线大公司在职工程师。
# - 现有的面试培训课程包括:九章算法班,系统设计班,算法强化班,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
                
        
        

 

Guess you like

Origin blog.csdn.net/zjy997/article/details/104666674