Clone Graph
Master this topic with zero to advance depth.
Clone Graph
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 (int) and a list (List[Node]) of its neighbors.
Visual Representation
1 -- 2
| |
4 -- 3
Clone:
1' -- 2'
| |
4' -- 3'Examples
Node 1 is connected to 2 and 4. Node 2 is connected to 1 and 3, etc.
Level II: Intermediate (BFS + HashMap)
Intuition
BFS uses a queue to visit nodes level-by-level. By using a HashMap to store original -> clone, we can manage complexity and cycles. Every time we encounter a neighbor, if it's not in the map, we clone it and add to the queue.
Thought Process
- Use a HashMap to store
originalNode -> clonedNode. - Push the start node to a queue and create its clone.
- While the queue is not empty:
- Pop
curr. For each neighbornbr:- If
nbris NOT in the map (unvisited):- Create its clone and add it to the map.
- Push
nbrto the queue.
- Add the
cloneMap.get(nbr)to thecloneMap.get(curr)'s neighbors list.
- If
- Pop
- Return the clone of the input node.
Pattern: BFS with Mapping
Detailed Dry Run
1 -- 2
| Map | Queue | Action |
|---|---|---|
| {1:1'} | [1] | Init |
| {1:1', 2:2'} | [2] | Pop 1, clone 2, add 2' to 1' neighbors |
| {1:1', 2:2'} | [] | Pop 2, 1 is in map, add 1' to 2' neighbors |
Level III: Optimal (DFS + HashMap)
Intuition
DFS is often more concise for graph cloning as it mimics the structure of the graph through the call stack. The HashMap acts as our "visited" set while also storing the deep copies.
Thought Process
- Use a HashMap to store
originalNode -> clonedNode. - In DFS function:
- If the node is NULL, return NULL.
- If the node is already in the map, return the existing clone.
- Otherwise, create a new clone and add it to the map.
- For each neighbor of the original node, recursively call DFS and add the result to the clone's neighbor list.
- Return the DFS call for the input node.
Pattern: DFS with Mapping
Detailed Dry Run
1 -> [2, 4]
| Map | Call | Action |
|---|---|---|
| {} | DFS(1) | Create 1', Map {1:1'}, Call DFS(2) |
| {1:1'} | DFS(2) | Create 2', Map {1:1', 2:2'}, Call DFS(3) |
| ... | ... | ... |
| {1:1', 2:2', 3:3', 4:4'} | DFS(4) | Return 4' to 1' neighbors list |
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.