Clone Graph

Question (LC.133)

Given a node in undirected graph, clone this graph.

Return a node in the cloned (deep copy) graph.

Analysis

Well we have to assume this graph is connected. Otherwise, there's no way to get to all vertices from the given vertex.

BFS Approach

The question wants you to recreate an adjacency list with the given start node.

Step 1 explore the whole graph by BFS
to find all the vertices first
Step 2 Clone all vertices (label)
Map<oldVertex, clonedVertex>
Step 3 Clone all edges (neighbors)
for each node copy the edge

Code

Graph explore with DFS

Graph explore with BFS

One-Go Approach

DFS is shorter to write because of the power of recursion. Just beware of the possible (call) stack overflow. We can intelligently utilize all the properties of DFS to produce the concise code below. During the previsit phrase, we can deep copy all the vertices. During backtracking, we can copy all the outgoing edges (neighbors) for that node using the base case to get the reference. When we are finished with the current node, we can return it to the previous node as a reference to its outgoing edge.

Last updated