-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path133. Clone Graph.py
47 lines (34 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
class Node:
def __init__(self, val = 0, neighbors = None):
self.val = val
self.neighbors = neighbors if neighbors is not None else []
from typing import Optional
class Solution:
# This is leetcodes solution. I think it's better.
def cloneGraph(self, node: Optional['Node']) -> Optional['Node']:
hm = dict()
def clone(node):
if node in hm: return hm[node]
copy = Node(node.val)
hm[node] = copy
for nextNode in node.neighbors:
copy.neighbors.append(clone(nextNode))
return copy
return clone(node) if node != None else None
def cloneGraph(self, node: Optional['Node']) -> Optional['Node']:
if node == None: return None
hashmap, visited = dict(), set()
def initNewNodes(n):
hashmap[n] = Node(n.val)
for nextNode in n.neighbors:
if nextNode not in hashmap:
initNewNodes(nextNode)
def addNeighbors(n):
visited.add(n.val)
for nextNode in n.neighbors:
hashmap[n].neighbors.append(hashmap[nextNode])
if nextNode.val not in visited:
addNeighbors(nextNode)
initNewNodes(node)
addNeighbors(node)
return hashmap[node]