-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy path133_Clone_Graph.py
More file actions
43 lines (40 loc) · 1.52 KB
/
Copy path133_Clone_Graph.py
File metadata and controls
43 lines (40 loc) · 1.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# 2015-10-1
# Definition for a undirected graph node
# class UndirectedGraphNode:
# def __init__(self, x):
# self.label = x
# self.neighbors = []
###########DFS Runtime: 204 ms##############
class Solution:
# @param node, a undirected graph node
# @return a undirected graph node
def cloneGraph(self, node):
if not node: return None
self.d = {} # key is original node, value is copy node
return self.dfs(node)
# @param n, a undirected graph node
# @return a its copy
def dfs(self, n):
if n in self.d: return self.d[n]
self.d[n] = UndirectedGraphNode(n.label)
for neighbor in n.neighbors:
self.d[n].neighbors.append(self.dfs(neighbor))
return self.d[n]
############ BFS Runtime: 84 ms ###############
class Solution(object):
def cloneGraph(self, node):
"""
:type node: UndirectedGraphNode
:rtype: UndirectedGraphNode
"""
if not node: return None
d = {node.label: UndirectedGraphNode(node.label)} # key is label, value is node
queue = collections.deque([node])
while queue:
poped = queue.popleft() # poped node must be in d
for neighbor in poped.neighbors:
if neighbor.label not in d: # new node found!
d[neighbor.label] = UndirectedGraphNode(neighbor.label)
queue.append(neighbor)
d[poped.label].neighbors.append(d[neighbor.label])
return d[node.label]