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.
class Node {
public int val;
public List<Node> neighbors;
}
Test case format:
For simplicity, each node's value is the same as the node's index (1-indexed). For example, the first node with val == 1
, the second node with val == 2
, and so on. The graph is represented in the test case using an adjacency list.
An adjacency list is a collection of unordered lists used to represent a finite graph. Each list describes the set of neighbors of a node in the graph.
The given node will always be the first node with val = 1
. You must return the copy of the given node as a reference to the cloned graph.
Example 1:
Input: adjList = [[2,4],[1,3],[2,4],[1,3]]
Output: [[2,4],[1,3],[2,4],[1,3]]
Explanation: There are 4 nodes in the graph.
1st node (val = 1)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).
2nd node (val = 2)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).
3rd node (val = 3)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).
4th node (val = 4)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).
Example 2:
Input: adjList = [[]]
Output: [[]]
Explanation: Note that the input contains one empty list. The graph consists of only one node with val = 1 and it does not have any neighbors.
Example 3:
Input: adjList = []
Output: []
Explanation: This an empty graph, it does not have any nodes.
Constraints:
[0, 100]
.1 <= Node.val <= 100
Node.val
is unique for each node.As always we look at the problems and it might seem pretty challenging. As I always suggest, if you feel stuck or don’t know how to approach the problem start with talking with yourself. So we have a graph and we need to clone it, one thought must immediately pop up in your head. There’s no way to make a full copy of something without full traverse/exploration of it. Good. What approaches do we know to traverse a graph/tree? Correct BFS(Bread First Search) or DFS(Depth First Search). Does it matter which one we pick? I don’t think so. We just made the first step on our way to the solution. Let’s look at simple DFS.
class Node
{
public int val;
public List<Node> neighbors;
public Node()
{
val = 0;
neighbors = new ArrayList<Node>();
}
public Node(int _val)
{
val = _val;
neighbors = new ArrayList<Node>();
}
public Node(int _val, ArrayList<Node> _neighbors)
{
val = _val;
neighbors = _neighbors;
}
}
public void traverseGraph(Node node)
{
LinkedList<Node> queue = new LinkedList<>();
Set<Node> visitedNodes = new HashSet<>();
queue.addLast(node);
while (!queue.isEmpty())
{
Node current = queue.removeFirst();
// we already visited this node, we should ship exploring this path
if (!visitedNodes.add(current))
{
continue;
}
// just because every node contains a list of it's neighbors we can add all of them to our queue
queue.addAll(current.neighbors);
}
}
So now we have the code to exploring given graph, but we need not only to visit them but also create a copy for each node in a graph. I intentionally not telling you anything about creating links between nodes we’re going to copy, I’ll touch it later on, for now let’s focus on our effort for creating copies. We need some data structure for storing relationship between original node and it’s copy. At the same time it should support 2 features, one for adding link and the second one for getting the copy. It should work as fast as possible. Some of you might have already guessed — HashMap in Java or HashTable in other programming languages. We need to add just few lines of code in our function.
public void traverseGraphAndCreateCopyOfNodes(Node node, Map<Node, Node> originalToCopyMap)
{
LinkedList<Node> queue = new LinkedList<>();
Set<Node> visitedNodes = new HashSet<>();
queue.addLast(node);
while (!queue.isEmpty())
{
Node current = queue.removeFirst();
// we already visited this node, we should ship exploring this path
if (!visitedNodes.add(current))
{
continue;
}
Node copy = new Node(current.val);
originalToCopyMap.put(current, copy);
// just because every node contains a list of it's neighbors we can add all of them to our queue
queue.addAll(current.neighbors);
}
}
Let’s have a look at what we have done so far. Let’s imagine we are given this graph
Then in our originalToCopyMap we have something like this
The only thing is left. We need somehow connect cloned nodes so they have exactly the same connections between them as the original graph has. How do we do that, can we utilize originalToCopyMap? The answer we must use it. We’re going to make the second traverse after we do the first one, using data from that map we can copy/establish connections between cloned nodes so they repeat the original.
public void traverseGraphAndCreateLinksBetweenNodes(Node node, Map<Node, Node> originalToCopyMap)
{
LinkedList<Node> queue = new LinkedList<>();
Set<Node> visitedNodes = new HashSet<>();
queue.addLast(node);
while (!queue.isEmpty())
{
Node current = queue.removeFirst();
// we already visited this node, we should ship exploring this path
if (!visitedNodes.add(current))
{
continue;
}
Node clonedCurrent = originalToCopyMap.get(current);
for (Node neighborOfCurrentNode: current.neighbors)
{
clonedCurrent.neighbors.add(originalToCopyMap.get(neighborOfCurrentNode));
}
// just because every node contains a list of it's neighbors we can add all of them to our queue
queue.addAll(current.neighbors);
}
}
After executing of the traverseGraphAndCreateLinksBetweenNodes method we should get this copied graph
Using 3 simple steps we solved the given problem. Here’s the full source code
Solution
class Node
{
public int val;
public List<Node> neighbors;
public Node()
{
val = 0;
neighbors = new ArrayList<Node>();
}
public Node(int _val)
{
val = _val;
neighbors = new ArrayList<Node>();
}
public Node(int _val, ArrayList<Node> _neighbors)
{
val = _val;
neighbors = _neighbors;
}
}
public Node cloneGraph(Node node) {
if (node == null)
{
return null;
}
Map<Node, Node> originalToCopyMap = new HashMap<>();
traverseGraphAndCreateCopyOfNodes(node, originalToCopyMap);
traverseGraphAndCreateLinksBetweenNodes(node, originalToCopyMap);
return originalToCopyMap.get(node);
}
public void traverseGraphAndCreateCopyOfNodes(Node node, Map<Node, Node> originalToCopyMap)
{
LinkedList<Node> queue = new LinkedList<>();
Set<Node> visitedNodes = new HashSet<>();
queue.addLast(node);
while (!queue.isEmpty())
{
Node current = queue.removeFirst();
// we already visited this node, we should ship exploring this path
if (!visitedNodes.add(current))
{
continue;
}
Node copy = new Node(current.val);
originalToCopyMap.put(current, copy);
// just because every node contains a list of it's neighbors we can add all of them to our queue
queue.addAll(current.neighbors);
}
}
public void traverseGraphAndCreateLinksBetweenNodes(Node node, Map<Node, Node> originalToCopyMap)
{
LinkedList<Node> queue = new LinkedList<>();
Set<Node> visitedNodes = new HashSet<>();
queue.addLast(node);
while (!queue.isEmpty())
{
Node current = queue.removeFirst();
// we already visited this node, we should ship exploring this path
if (!visitedNodes.add(current))
{
continue;
}
Node clonedCurrent = originalToCopyMap.get(current);
for (Node neighborOfCurrentNode: current.neighbors)
{
clonedCurrent.neighbors.add(originalToCopyMap.get(neighborOfCurrentNode));
}
// just because every node contains a list of it's neighbors we can add all of them to our queue
queue.addAll(current.neighbors);
}
}
We can stop right here and be happy about another solved problem. BUT some of you might have noticed we have some duplicates in our code which we can remove and let’s use recursion to make our code cleaner and shorter.
public Node cloneGraph(Node node)
{
Map<Node, Node> map = new HashMap<>();
return cloneGraph(node, map);
}
private Node cloneGraph(Node node, Map<Node, Node> map)
{
if (node == null)
{
return null;
}
if (map.containsKey(node))
{
return map.get(node);
}
Node copy = new Node(node.val);
map.put(node, copy);
for (Node neighbor : node.neighbors)
{
copy.neighbors.add(cloneGraph(neighbor, map));
}
return copy;
}
Recursive approach
I hope this article will help you to understand the logic behind this problem and use it to solve other tasks.
See you soon!
Also Published Here
Photo by Thomas Couillard on Unsplash