leetcode------Clone Graph

标题: 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

 

posted @ 2015-04-12 15:40  pku_smile  阅读(154)  评论(0编辑  收藏  举报