Sponsored
Sponsored
The Depth-First Search (DFS) approach is one of the most intuitive ways to solve the graph cloning problem. Here, we will recursively explore each node starting from the root (Node 1) and keep a map to store already cloned nodes, ensuring each node is cloned once.
For each node, we:
Time Complexity: O(V+E), where V is the number of vertices and E is the number of edges. This is because we visit each node and edge once.
Space Complexity: O(V), for the recursion stack and the clone map.
1class Node:
2 def __init__(self, val = 0, neighbors = None):
3 self.val = val
4 self.neighbors = neighbors if neighbors is not None else []
5
6class Solution:
7 def __init__(self):
8 self.visited = {}
9
10 def cloneGraph(self, node: 'Node') -> 'Node':
11 if not node:
12 return None
13
14 if node in self.visited:
15 return self.visited[node]
16
17 clone_node = Node(node.val, [])
18 self.visited[node] = clone_node
19
20 if node.neighbors:
21 clone_node.neighbors = [self.cloneGraph(n) for n in node.neighbors]
22
23 return clone_nodeThis Python implementation uses a dictionary visited to map original nodes to their clones. The cloneGraph function recursively creates and returns deep copies by processing neighbors recursively.
An alternative approach is to use Breadth-First Search (BFS), which is iterative in nature. Here, we utilize a queue to help explore each node level by level, preventing deep recursion and managing each node's clone in a breadth-wise manner.
In this BFS approach:
Time Complexity: O(V+E).
Space Complexity: O(V).
1
The Python BFS implementation uses a deque for iterative traversal and a dictionary visited to record cloned nodes. It features level-wise cloning and linking of the nodes, ensuring all nodes are cloned and linked efficiently.