From f82f41e6106d73e049c1193ef45f304d8a98089f Mon Sep 17 00:00:00 2001 From: sumanth-botlagunta Date: Sat, 8 Apr 2023 22:49:25 +0530 Subject: [PATCH] 133: clone graph --- python/clone_graph.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 python/clone_graph.py diff --git a/python/clone_graph.py b/python/clone_graph.py new file mode 100644 index 0000000..35fd538 --- /dev/null +++ b/python/clone_graph.py @@ -0,0 +1,19 @@ +# https://leetcode.com/problems/clone-graph/description/ +# T: O(n) where n is the number of nodes in the graph +# S: O(n) where n is the number of nodes in the graph + +class Solution: + def cloneGraph(self, node: 'Node') -> 'Node': + if not node: + return node + d = {node.val: Node(node.val, [])} + q = deque([node]) + while q: + cur_node = q.pop() + cur_res = d[cur_node.val] + for n in cur_node.neighbors: + if n.val not in d: + q.append(n) + d[n.val] = Node(n.val, []) + cur_res.neighbors.append(d[n.val]) + return d[node.val]