Skip to content

Latest commit

 

History

History
12 lines (10 loc) · 512 Bytes

File metadata and controls

12 lines (10 loc) · 512 Bytes

Deep copy an undirected graph. (There could be cycles in the original graph)

solution

We need to copy all the nodes and all the edges.

  1. iterate all nodes in graph
  2. when we iterate each node, we need to copy the node and copy all the outgoing edges from the current node.
    We can use a map to map the origin vertex to the copied vertex.

time: O(E + V)
space: O(V)

follow up: Make a reversed copy of the given directed graph

We just need to reverse the edge when we add the copy to it.