Clone Graph - Problem
You're given a reference to a node in a connected undirected graph. Your task is to create a complete deep copy (clone) of the entire graph.
Each node in the graph contains:
- An integer
val(the node's value) - A
List<Node>of its neighbors
The graph is connected, meaning you can reach any node from any other node. You need to return a reference to the cloned version of the given node.
Important: The cloned graph should be completely independent of the original - modifying the clone shouldn't affect the original graph.
Node Definition:
class Node {
public int val;
public List<Node> neighbors;
} Input & Output
example_1.py β Simple 2-node cycle
$
Input:
adjList = [[2],[1]]
βΊ
Output:
[[2],[1]]
π‘ Note:
The graph has 2 nodes. Node 1 is connected to node 2, and node 2 is connected to node 1. The cloned graph maintains the same structure.
example_2.py β 4-node complex graph
$
Input:
adjList = [[2,4],[1,3],[2,4],[1,3]]
βΊ
Output:
[[2,4],[1,3],[2,4],[1,3]]
π‘ Note:
Node 1 connects to nodes 2 and 4. Node 2 connects to nodes 1 and 3. Node 3 connects to nodes 2 and 4. Node 4 connects to nodes 1 and 3. The clone preserves all connections.
example_3.py β Single node
$
Input:
adjList = [[]]
βΊ
Output:
[[]]
π‘ Note:
The graph contains only one node with no neighbors. The cloned graph is identical.
Constraints
- The number of nodes in the graph is in the range [0, 100]
- 1 β€ Node.val β€ 100
- Node.val is unique for each node
- There are no repeated edges and no self-loops in the graph
- The graph is connected and you can visit all nodes from the given node
Visualization
Tap to expand
Understanding the Visualization
1
Start with Original
Begin with a reference to one node in the original graph
2
Create Clone Map
Use a HashMap to track which nodes have been cloned
3
BFS Traversal
Visit nodes level by level, cloning unvisited neighbors
4
Connect Clones
Link cloned nodes together maintaining original relationships
5
Return Clone
Return reference to the cloned starting node
Key Takeaway
π― Key Insight: HashMap prevents infinite loops while BFS ensures systematic traversal. Each original node maps to exactly one clone, preserving the graph's structure perfectly.
π‘
Explanation
AI Ready
π‘ Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code