标签:
标题: | Clone Graph |
通过率: | 23.7% |
难度: | 中等 |
Nodes are labeled uniquely.
We use#
as a separator for each node, and ,
as a separator for node label and each neighbor of the node.
As an example, consider the serialized graph {0,1,2#1,2#2,2}
.
The graph has a total of three nodes, and therefore contains three parts as separated by #
.
0
. Connect node 0
to both nodes 1
and 2
.1
. Connect node 1
to node 2
.2
. Connect node 2
to node 2
(itself), thus forming a self-cycle.
Visually, the graph looks like the following:
1 / / 0 --- 2 / \_/
1 # Definition for a undirected graph node 2 # class UndirectedGraphNode: 3 # def __init__(self, x): 4 # self.label = x 5 # self.neighbors = [] 6 7 class Solution: 8 # @param node, a undirected graph node 9 # @return a undirected graph node 10 def cloneGraph(self, node): 11 if node == None: return None 12 nodeMap={} 13 return self.cloneNode(node,nodeMap) 14 15 16 def cloneNode(self,node,nodeMap): 17 if node == None:return None 18 if nodeMap.has_key(node): 19 return nodeMap[node] 20 else : 21 clone =UndirectedGraphNode(node.label) 22 nodeMap[node]=clone 23 for nei in node.neighbors: 24 clone.neighbors.append(self.cloneNode(nei,nodeMap)) 25 return clone
标签:
原文地址:http://www.cnblogs.com/pkuYang/p/4419592.html