Problem
Given a reference of a node in a connected undirected graph, return a deep copy (clone
) of the graph. Each node in the graph contains a val (int
) and a list (List[Node]
) of its neighbors.
Example:
1 |
|
1 |
|
Note:
- The number of nodes will be between 1 and 100.
- The undirected graph is a simple graph, which means no repeated edges and no self-loops in the graph.
- Since the graph is undirected, if node p has node q as neighbor, then node q must have node p as neighbor too.
- You must return the copy of the given node as a reference to the cloned graph.
Explanation
-
First, we want to create copy of every node first regardless their neighbors. We can achieve this by creating a queue, push the unvisited node inside the queue, and we create a hashmap which connect original node with a new copy of the node. If the map contains the node, then it means this node is visited and we don’t add to the queue.
-
Next, we want to connect the result node with its neighbors. Since we have a map connect the original node with the same result node. We can easily loop through each original node’s neighbors, and we use the map to get the node and connect its neighbors to the same neighbors as the original node using the hashmap.
Solution
1 |
|