-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path#133. Clone Graph.py
51 lines (36 loc) · 1.33 KB
/
#133. Clone Graph.py
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
44
45
46
47
48
49
50
51
#133. Clone Graph
"""
# Definition for a Node.
class Node:
def __init__(self, val = 0, neighbors = None):
self.val = val
self.neighbors = neighbors if neighbors is not None else []
"""
class Solution:
def cloneGraph(self, node: 'Node') -> 'Node':
self.q = [node]
self.visit = {}
self.visit[node] = Node(node.val,[])
while self.q:
curr = self.q.pop()
for n in curr.neighbors:
if n not in self.visit:
cl_node = Node(n.val,[])
self.visit[n] = cl_node
self.q.append(n)
self.visit[curr].neighbors.append(self.visit[n])
return self.visit[node]
#M2 dfs
# self.visit = {}
# def dfs(node):
# if not node:
# return node
# if node in self.visit:
# return self.visit[node]
# else:
# cl_node = Node(node.val,[])
# self.visit[node] = cl_node
# if node.neighbors:
# cl_node.neighbors = [ dfs(n) for n in node.neighbors]
# return cl_node
# return dfs(node)