Skip to content

Commit 06c1ddc

Browse files
solves clone graph (#133) in python
1 parent f9079e5 commit 06c1ddc

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

python/clone_graph.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
# https://leetcode.com/problems/clone-graph/description/
2+
# T: O(n) where n is the number of nodes in the graph
3+
# S: O(n) where n is the number of nodes in the graph
4+
5+
class Solution:
6+
def cloneGraph(self, node: 'Node') -> 'Node':
7+
if not node:
8+
return node
9+
d = {node.val: Node(node.val, [])}
10+
q = deque([node])
11+
while q:
12+
cur_node = q.pop()
13+
cur_res = d[cur_node.val]
14+
for n in cur_node.neighbors:
15+
if n.val not in d:
16+
q.append(n)
17+
d[n.val] = Node(n.val, [])
18+
cur_res.neighbors.append(d[n.val])
19+
return d[node.val]

0 commit comments

Comments
 (0)