File tree 1 file changed +32
-0
lines changed
1 file changed +32
-0
lines changed Original file line number Diff line number Diff line change
1
+ # 133. Clone Graph
2
+
3
+ ## Dictionary and DFS Solution
4
+ - Runtime: O(V + E)
5
+ - Space: O(V)
6
+ - V = Vertices
7
+ - E = Edges
8
+
9
+ We can use a dictionary as a map to the cloned node, then by using DFS, we can figure out the cloned node in relation to the nodes in the graph.
10
+ As we visit each node with DFS, we can create a clone of each neighbor and add them to the current node's cloned node using the dictionary.
11
+ After that, we can call DFS on each neighbor.
12
+
13
+ ```
14
+ class Solution:
15
+ def cloneGraph(self, node: 'Node') -> 'Node':
16
+
17
+ def dfs_clone(curr):
18
+ if curr in visited:
19
+ return
20
+ visited.add(curr)
21
+ for neighbor in curr.neighbors:
22
+ if neighbor not in node_to_clone:
23
+ node_to_clone[neighbor] = Node(neighbor.val, [])
24
+ node_to_clone[curr].neighbors.append(node_to_clone[neighbor])
25
+ dfs_clone(neighbor)
26
+
27
+ node_to_clone = dict()
28
+ node_to_clone[node] = Node(node.val, [])
29
+ visited = set()
30
+ dfs_clone(node)
31
+ return node_to_clone[node]
32
+ ```
You can’t perform that action at this time.
0 commit comments