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.
1function Node(val, neighbors) {
2 this.val = val;
3 this.neighbors = neighbors ? neighbors : [];
4};
5
6var cloneGraph = function(node) {
7 let visited = new Map();
8
9 function dfs(node) {
10 if (!node) return node;
11 if (visited.has(node)) return visited.get(node);
12
13 let cloneNode = new Node(node.val);
14 visited.set(node, cloneNode);
15
16 node.neighbors.forEach(neighbor => {
17 cloneNode.neighbors.push(dfs(neighbor));
18 });
19
20 return cloneNode;
21 }
22
23 return dfs(node);
24};
The JavaScript implementation uses a Map to keep track of visited nodes during the DFS traversal. The cloneGraph
creates clones while traversing and uses stored clones for previously visited nodes, ensuring an acyclic processing.
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#include <vector>
2#include <unordered_map>
3#include <queue>
4using namespace std;
5
6class Node {
7public:
8 int val;
9 vector<Node*> neighbors;
10 Node() {
11 val = 0;
12 neighbors = vector<Node*>();
13 }
14 Node(int _val) {
15 val = _val;
16 neighbors = vector<Node*>();
17 }
18 Node(int _val, vector<Node*> _neighbors) {
19 val = _val;
20 neighbors = _neighbors;
21 }
22};
23
24class Solution {
25public:
26 Node* cloneGraph(Node* node) {
27 if (!node) return NULL;
28 unordered_map<Node*, Node*> visited;
29 queue<Node*> q;
30 q.push(node);
31 visited[node] = new Node(node->val);
32
33 while (!q.empty()) {
34 auto n = q.front(); q.pop();
35 for (auto neighbor : n->neighbors) {
36 if (visited.find(neighbor) == visited.end()) {
37 visited[neighbor] = new Node(neighbor->val);
38 q.push(neighbor);
39 }
40 visited[n]->neighbors.push_back(visited[neighbor]);
41 }
42 }
43 return visited[node];
44 }
45};
This C++ BFS-based solution utilizes a queue to explore nodes level by level. We maintain a map visited
to keep track of the original to clone node mapping. Each node and its neighbors are iteratively visited, cloned, and linked.