Clone Graph
Make a full copy of a connected graph, with new nodes joined by the same links.
Given one node of a connected undirected graph, return a deep copy of the whole graph. Each node has an integer value valneighbors
The examples write a graph as adjList
Example 1
Output: [[2, 4], [1, 3], [2, 4], [1, 3]]
Explanation: four nodes in a square, 1 - 2 - 3 - 4 - 1.
Example 2
Output: []
Explanation: the graph is empty, so the given node is null.
The Idea
Copying a road map by hand is a good picture of this problem. You draw a new dot for every town and a new line for every road, and the new map shows the same towns with the same roads. Nothing on the new sheet is cut out of the old one.
Example 1 is a small map of that kind. Its first entry, [2, 4][1, 3]
We only hold node 1, though. To reach the others we follow its neighbours, then their neighbours. Suppose we copy node 1, then go to its first neighbour, 2, and copy it. Node 2 lists 1 as a neighbour, so following the links leads back to 1. Should we copy 1 again?
No. A second copy of 1 would break the square, and the walk 1, 2, 1, 2, ... would never stop. The copy of 2 has to link to the copy of 1 that already exists. So while copying, we must remember which original node got which copy. Look at the picture below.
The original graph is on the left and its finished copy on the right, where 1' is the copy of 1, 2' the copy of 2, and so on. In the middle is the copies map, one row per original node with its copy. The highlighted row, 1 → 1', is what copying 2 finds when it reaches neighbour 1 again, so the highlighted link 2' - 1' goes to that same 1'.
The rest of the walk goes the same way. From 2 we go on to 3 and copy it, and from 3 to 4. All of the neighbours of 4, namely 1 and 3, are in the copies map already, so the walk turns back. Going as deep along the links as possible before turning back is called depth-first search, or DFS. Back at 1, its second neighbour, 4, is in the map too, and the copy is complete.
Solution Approach
Turning that idea into code means settling three things: how to copy one node and reach the rest, how to avoid copying a node twice, and when to write a new copy into the copies map. A version with a queue of nodes to visit comes as an option at the end.
Copying one node and its neighbours
What does copying a single node involve? Make a new node with the same val
Copying each node only once
What stops the walk on the square from running forever? Without memory, the copy of 1 asks for a copy of 2, which asks for a copy of 1, and so on. The copies map stops it, and it also keeps the square from getting a second copy of 1. The method looks the node up first, and if a copy is there, returns that copy and goes no deeper.
The map is a HashMapNodeequalsval
When to record a new copy
Does the order inside the method matter? It does. The new node must go into the copies map as soon as it is made, before the loop over its neighbours. On the square, copying 1 leads to 2, and 2 leads back to 1 while 1 is still busy with its list. If 1 → 1' were written only after that list, 2 would not find it.
Optional: a queue instead of recursion
Each recursive call stays open until its neighbours are copied. Java keeps the open calls on its call stack, an area of memory with a fixed size, so a graph shaped like one long line makes the stack as deep as the line is long. The same copy can be made with a queue of nodes still to visit and a loop. That order, which copies all neighbours of a node before moving further away, is called breadth-first search, or BFS. It uses the same copies map.
Java Solution
The method cloneGraph
- First, create the copies map, an empty
namedHashMap , and pass it with the given node to the recursive helpercopies . A new map for every call tocopy means a second graph is never mixed with the first.cloneGraph - In
, returncopy when the node isnull , which is the empty graph of Example 2.null - Look the node up in
. If the lookup finds a copy, namedcopies , return it.done - Otherwise create
, a new node with the sameclone , and put the pair node →val intoclone straight away.copies - Loop over the original's neighbours. For each neighbour, named
, callnext and add the node it returns to the neighbour list ofcopy . Then returnclone .clone
Around the method sit a small NodemainbuildallNodestoAdjListmain
import java.util.ArrayList;
import java.util.ArrayDeque;
import java.util.Collections;
import java.util.Deque;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class CloneGraph {
static class Node {
int val;
List<Node> neighbors = new ArrayList<>();
Node(int val) { this.val = val; }
}
public static Node cloneGraph(Node node) {
return copy(node, new HashMap<>());
}
private static Node copy(Node node, Map<Node, Node> copies) {
if (node == null) {
return null; // empty graph
}
Node done = copies.get(node);
if (done != null) {
return done; // copied already: reuse that copy
}
Node clone = new Node(node.val);
copies.put(node, clone); // record it before visiting neighbours
for (Node next : node.neighbors) {
clone.neighbors.add(copy(next, copies));
}
return clone;
}
// Builds the graph from its adjacency list; entry i lists the neighbours of node i + 1.
static Node build(int[][] adjList) {
if (adjList.length == 0) {
return null;
}
Node[] nodes = new Node[adjList.length];
for (int i = 0; i < nodes.length; i++) {
nodes[i] = new Node(i + 1);
}
for (int i = 0; i < nodes.length; i++) {
for (int v : adjList[i]) {
nodes[i].neighbors.add(nodes[v - 1]);
}
}
return nodes[0];
}
// Collects every node reachable from start, each object once.
static Set<Node> allNodes(Node start) {
Set<Node> seen = Collections.newSetFromMap(new IdentityHashMap<>());
Deque<Node> todo = new ArrayDeque<>();
if (start != null) {
todo.add(start);
}
while (!todo.isEmpty()) {
Node n = todo.poll();
if (seen.add(n)) {
todo.addAll(n.neighbors);
}
}
return seen;
}
// Writes the graph back as an adjacency list, ordered by node value.
static String toAdjList(Node start) {
List<Node> nodes = new ArrayList<>(allNodes(start));
nodes.sort((a, b) -> Integer.compare(a.val, b.val));
List<List<Integer>> rows = new ArrayList<>();
for (Node n : nodes) {
List<Integer> row = new ArrayList<>();
for (Node m : n.neighbors) {
row.add(m.val);
}
rows.add(row);
}
return rows.toString();
}
static void run(int[][] adjList) {
Node original = build(adjList);
Node clone = cloneGraph(original);
Set<Node> shared = allNodes(original);
shared.retainAll(allNodes(clone));
System.out.println(toAdjList(clone) + " shared with the original: " + shared.size());
}
public static void main(String[] args) {
run(new int[][] {{2, 4}, {1, 3}, {2, 4}, {1, 3}});
run(new int[][] {});
run(new int[][] {{}});
run(new int[][] {{2}, {1}});
run(new int[][] {{2, 3}, {1, 3}, {1, 2}});
}
}
Running it prints:
[[2, 4], [1, 3], [2, 4], [1, 3]] shared with the original: 0
[] shared with the original: 0
[[]] shared with the original: 0
[[2], [1]] shared with the original: 0
[[2, 3], [1, 3], [1, 2]] shared with the original: 0
Look at the first line: the copy of the square reads [[2, 4], [1, 3], [2, 4], [1, 3]][]
The line [[]]
The placement of copies.put(node, clone)StackOverflowError
Complexity
Here V is the number of nodes and E the number of links, and the copies map keeps the work to one visit per node.
- Time: O(V + E), because each of the V nodes is copied once and its neighbour list read once, and each link appears in two lists, so the loops take 2E steps in total.
- Space: O(V) besides the copy, because the copies map holds one pair per node, and the recursion can be V calls deep on a graph shaped like one long line.
The same map from original to copy also solves