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

  1. Use HashMap to map original node → cloned node
  2. DFS: If node already cloned (in map), return clone
  3. Create clone, add to map, then clone neighbors recursively
  4. BFS works too: clone node, add to queue, process neighbors

Related Data Structures & Algorithms exercises

Practice all Data Structures & Algorithms exercises · Run this idea in the Java compiler