Skip to content
BytePatterns

Deep Copy A Graph

MediumGraphs#dfs#hash-map~30m

Problem

Given a reference to one node of a connected undirected graph, build an independent copy of the whole graph and return the matching node. Every node in the copy must be a new object, and the copy must have exactly the same connections as the original. The graph may contain cycles, and an absent reference copies to nothing.

Examples

Input:  a square: 1 - 2 - 3 - 4 - 1
Output: a new square with the same four labels and the same four links
Input:  the same square, comparing the copied node with the original
Output: they are different objects
Why:    sharing even one node would make it a shallow copy
Input:  no node at all
Output: nothing
Why:    edge case, there is no graph to copy

Hints

0 / 3

Stuck on the idea rather than the code? Depth-First Search covers it.