The problem “133. Clone Graph” on LeetCode is as follows:
Given a reference of a node in a connected undirected graph, return a deep copy (clone) of the graph. Each node in the graph contains a value (val
) and a list (List[Node]
) of its neighbors.
class Node {
public int val;
public List<Node> neighbors;
}
val
is unique, we will assume it for simplicity in cloning the graph.null
)?
null
, we should return null
.To deep clone the graph, we will use Depth-First Search (DFS) approach with a hashmap to store the original nodes and their corresponding cloned nodes. This ensures we map each original node to its clone and avoid duplication.
Here is a step-by-step strategy:
null
, return null
.import java.util.*;
class Node {
public int val;
public List<Node> neighbors;
public Node() {
val = 0;
neighbors = new ArrayList<Node>();
}
public Node(int _val) {
val = _val;
neighbors = new ArrayList<Node>();
}
public Node(int _val, ArrayList<Node> _neighbors) {
val = _val;
neighbors = _neighbors;
}
}
public class Solution {
private Map<Node, Node> map = new HashMap<>();
public Node cloneGraph(Node node) {
if (node == null) {
return null;
}
return clone(node);
}
private Node clone(Node node) {
if (map.containsKey(node)) {
return map.get(node);
}
Node cloneNode = new Node(node.val, new ArrayList<>());
map.put(node, cloneNode);
for (Node neighbor : node.neighbors) {
cloneNode.neighbors.add(clone(neighbor));
}
return cloneNode;
}
}
Time Complexity: The time complexity is (O(V + E)), where (V) is the number of vertices (nodes) and (E) is the number of edges. This is because each node and each edge is visited once.
Space Complexity: The space complexity is (O(V)). This accounts for the space used by the HashMap and the recursion stack in the DFS.
This solution ensures that every node and its corresponding edges are cloned exactly once, preserving the original graph structure.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?