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
                
        
        

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章