Posted on 2023-04-08 18:48
Uriel 阅读(43)
评论(0) 编辑 收藏 引用 所属分类:
搜索 、
图论 、
闲来无事重切Leet Code
克隆一个无向图,可能有环,直接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, {})