ntree.aiClone Graph
Solutions
1. Depth First Search
O(V + E) time | O(V) space, for V nodes and E edges
Intuition
We can traverse through the graph with DFS and copy every node, keeping each copy in a hash map.
When we reach a node that was already visited, we use the copy from the hash map instead of creating a new one.
Algorithm
- Create a
dfsfunction taking a node and a hash map from a node to its copy.- Return the copy in the hash map when the node is already there.
- Copy the node and put the copy in the hash map.
- Set the neighbours of the copy to
dfscalled with every neighbour of the node. - Return the copy.
- Call
dfswith the given node and an empty hash map.
1
2
3
4
1→1
1
visit 1, copy
1 / 10
1
2
3
4
→
→
→
→
Code
Code
def cloneGraph(node: GraphNode) -> GraphNode:
return dfs(node, {})
def dfs(node: GraphNode, copies: dict[GraphNode, GraphNode]) -> GraphNode:
if node in copies:
return copies[node]
clone = GraphNode(node.val)
copies[node] = clone
clone.neighbors = [dfs(neighbour, copies) for neighbour in node.neighbors]
return clone
/**
* @param {GraphNode} node
* @returns {GraphNode}
*/
var cloneGraph = function (node) {
return dfs(node, new Map())
}
function dfs(node, copies) {
if (copies.has(node)) return copies.get(node)
const clone = new GraphNode(node.val)
copies.set(node, clone)
clone.neighbors = node.neighbors.map(neighbour => dfs(neighbour, copies))
return clone
}
import java.util.HashMap;
import java.util.Map;
class Solution {
public GraphNode cloneGraph(GraphNode node) {
return dfs(node, new HashMap<>());
}
private GraphNode dfs(GraphNode node, Map<GraphNode, GraphNode> copies) {
GraphNode made = copies.get(node);
if (made != null) return made;
made = new GraphNode(node.val);
copies.put(node, made);
for (GraphNode neighbour : node.neighbors) made.neighbors.add(dfs(neighbour, copies));
return made;
}
}
2. Breadth First Search
O(V + E) time | O(V) space, for V nodes and E edges
Intuition
We can traverse through the graph with BFS and copy every node, keeping each copy in a hash map.
When we reach a node that was already visited, we use the copy from the hash map instead of creating a new one.
Algorithm
- Copy the given node, put the copy in a hash map, and put the node in a queue.
- Take a node from the queue while the queue is not empty and traverse through its neighbours.
- For each iteration:
- Copy the neighbour and add it to the queue when it is not in the hash map yet.
- Add the copy of the neighbour to the neighbours of the copy of the node.
- Return the copy of the given node.
1
2
3
4
1→1
1
visit 1, copy
1 / 10
1
2
3
4
→
→
→
→
Code
Code
from collections import deque
def cloneGraph(node: GraphNode) -> GraphNode:
copies = {node: GraphNode(node.val)}
queue = deque([node])
while queue:
current = queue.popleft()
for neighbour in current.neighbors:
if neighbour not in copies:
copies[neighbour] = GraphNode(neighbour.val)
queue.append(neighbour)
copies[current].neighbors.append(copies[neighbour])
return copies[node]
/**
* @param {GraphNode} node
* @returns {GraphNode}
*/
var cloneGraph = function (node) {
const copies = new Map([[node, new GraphNode(node.val)]])
const queue = [node]
for (let at = 0; at < queue.length; at++) {
const current = queue[at]
for (const neighbour of current.neighbors) {
if (!copies.has(neighbour)) {
copies.set(neighbour, new GraphNode(neighbour.val))
queue.push(neighbour)
}
copies.get(current).neighbors.push(copies.get(neighbour))
}
}
return copies.get(node)
}
import java.util.ArrayDeque;
import java.util.HashMap;
import java.util.Map;
import java.util.Queue;
class Solution {
public GraphNode cloneGraph(GraphNode node) {
Map<GraphNode, GraphNode> copies = new HashMap<>();
copies.put(node, new GraphNode(node.val));
Queue<GraphNode> queue = new ArrayDeque<>();
queue.add(node);
while (!queue.isEmpty()) {
GraphNode current = queue.remove();
for (GraphNode neighbour : current.neighbors) {
if (!copies.containsKey(neighbour)) {
copies.put(neighbour, new GraphNode(neighbour.val));
queue.add(neighbour);
}
copies.get(current).neighbors.add(copies.get(neighbour));
}
}
return copies.get(node);
}
}
Was the explanation clear?
# Definitions:# class GraphNode:# def __init__(self, val=0, neighbors=None):# self.val = val# self.neighbors = neighbors if neighbors is not None else [] def cloneGraph(node: GraphNode) -> GraphNode: pass 1
2
3
4
Press Visualise to step through your code.