Clone Graph in Java: Explanation & Practice
Create a deep copy of an undirected graph
Problem summary
Given a reference of a node in a connected undirected graph, return a deep copy (clone) of the graph. Use HashMap to track cloned nodes.
Starter code
public class Main {
public static void main(String[] args) {
// Graph: 1 -- 2
// | |
// 4 -- 3
// Clone the entire graph
// Use HashMap<original, clone> to track
// Print: Cloned successfully
}
}Expected output and test cases
- 4-node cycle
Cloned successfully
- Single node
Cloned successfully
- Empty graph
Cloned successfully
Hints
- Use HashMap to map original node → cloned node
- DFS: If node already cloned (in map), return clone
- Create clone, add to map, then clone neighbors recursively
- BFS works too: clone node, add to queue, process neighbors
Related Data Structures & Algorithms exercises
- Practice Lowest Common Ancestor in Java
- Practice Number of Islands in Java
- Practice Course Schedule (Cycle Detection) in Java
Practice all Data Structures & Algorithms exercises · Run this idea in the Java compiler