Algo-Sim › Graph Traversal
Clone Graph
Medium · Graph Traversal · step through it in Java, Python and C++ on your own input
Return a deep copy of a connected undirected graph. DFS with a map from each original node to its copy, filled before visiting neighbours.
Problem
Given a node of a connected undirected graph, where each node has a value and a list of neighbours, return a deep copy of the whole graph: new nodes with the same values and the same connections, sharing nothing with the original.
Constraints
- 0 ≤ number of nodes ≤ 100
- 1 ≤ Node.val ≤ 100, and node i has value i
- No repeated edges or self-loops
- Cycles mean a node must not be copied twice
Edge cases to test
- An empty graph (null)
- One node with no neighbours
- A node that is its own neighbour
Follow-up questions
- Why put the copy in the map before visiting neighbours?
- A cycle leads back to the node; finding its copy in the map stops infinite recursion.
- DFS or BFS?
- Either: both visit each node and edge once, O(V + E). BFS avoids deep recursion.
Solution
Java
private Map<Node, Node> clones = new HashMap<>();
public Node cloneGraph(Node node) {
if (node == null) return null;
if (clones.containsKey(node)) return clones.get(node);
Node copy = new Node(node.val);
clones.put(node, copy);
for (Node next : node.neighbors) {
copy.neighbors.add(cloneGraph(next));
}
return copy;
}Python
clones = {}
def clone_graph(node):
if node is None:
return None
if node in clones:
return clones[node]
copy = Node(node.val)
clones[node] = copy
for nxt in node.neighbors:
copy.neighbors.append(clone_graph(nxt))
return copyC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
unordered_map<Node *, Node *> clones = {};
Node *cloneGraph(Node *node) {
if (node == nullptr)
return nullptr;
if (clones.count(node))
return clones[node];
Node *copy = new Node(node->val);
clones[node] = copy;
for (Node *next : node->neighbors) {
copy->neighbors.push_back(cloneGraph(next));
}
return copy;
}
};
More Graph Traversal problems
- Breadth-First Search (Easy)
- Depth-First Search (Easy)
- Course Schedule (cycle detection) (Medium)
- Graph Valid Tree (undirected cycle) (Medium)
- Number of Connected Components (DFS) (Medium)
- Is Graph Bipartite? (Medium)
- Word Ladder (Hard)
- Open the Lock (Medium)