码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode------Clone Graph

时间:2015-04-12 16:03:28      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:

标题: Clone Graph
通过率: 23.7%
难度: 中等
OJ‘s undirected graph serialization:

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 #.

  1. First node is labeled as 0. Connect node 0 to both nodes 1 and 2.
  2. Second node is labeled as 1. Connect node 1 to node 2.
  3. Third node is labeled as 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

 

leetcode------Clone Graph

标签:

原文地址:http://www.cnblogs.com/pkuYang/p/4419592.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!