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