Uriel's Corner

Research Associate @ Harvard University / Research Interests: Computer Vision, Biomedical Image Analysis, Machine Learning
posts - 0, comments - 50, trackbacks - 0, articles - 594
克隆一个无向图,可能有环,直接DFS


 1 #133
 2 #Runtime: 41 ms (Beats 39.30%)
 3 #Memory: 13.8 MB (Beats 37.71%)
 4 
 5 """
 6 # Definition for a Node.
 7 class Node(object):
 8     def __init__(self, val = 0, neighbors = None):
 9         self.val = val
10         self.neighbors = neighbors if neighbors is not None else []
11 """
12 
13 class Solution(object):
14     def cloneGraph(self, node):
15         """
16         :type node: Node
17         :rtype: Node
18         """
19         def DFS(node, cloned_graph):
20             if node not in cloned_graph:
21                 cloned_graph[node] = Node(node.val)
22                 for nr in node.neighbors:
23                     cloned_graph[node].neighbors.append(DFS(nr, cloned_graph))
24             return cloned_graph[node]
25         if node == None:
26             return None
27         return DFS(node, {})

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理