-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path133. Clone Graph.py
41 lines (34 loc) · 933 Bytes
/
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
"""
# Definition for a Node.
class Node:
def __init__(self, val, neighbors):
self.val = val
self.neighbors = neighbors
"""
class Solution:
def cloneGraph(self, node: 'Node') -> 'Node':
if not node:
return None
ol = []
od = {}
i = 0
orign = node
rl = []
ocur = [node]
while ocur:
newocur = []
while ocur:
o = ocur.pop(0)
if o not in od:
ol.append(o)
rl.append(Node(o.val, []))
od[o] = i
i += 1
for onei in o.neighbors:
newocur.append(onei)
ocur = newocur
for i in range(len(ol)):
for nei in ol[i].neighbors:
index = od.get(nei)
rl[i].neighbors.append(rl[index])
return rl[0]