PracticeNeetCode ↗LeetCode ↗
Given a reference to a node in a connected undirected graph, return a deep copy of the entire graph. Every node holds a value and a list of neighbor references.
None, return None.old_to_new.dfs(neighbor) to the clone's list, and return the clone.dfs on the starting node and return the result.Time: O(V + E) — Space: O(V)
class Node:
def __init__(self, val=0, neighbors=None):
self.val = val
self.neighbors = neighbors if neighbors is not None else []
def cloneGraph(node: "Node") -> "Node":
old_to_new = {}
def dfs(n: "Node") -> "Node":
if n in old_to_new:
return old_to_new[n]
copy = Node(n.val)
old_to_new[n] = copy
for neighbor in n.neighbors:
copy.neighbors.append(dfs(neighbor))
return copy
return dfs(node) if node else NoneHow the solution above works, piece by piece.
old_to_new maps each original node to its copy; it doubles as the visited set.dfs(neighbor) returns its copy, which is appended to the copy's neighbour list.Running it on the 4-node example [[2, 4], [1, 3], [2, 4], [1, 3]]:
old → copy in the map before visiting neighbours, then links the copy to the copies of its neighbours. When the DFS comes back around to node 1, the map returns the existing copy instead of looping forever.