medium

Clone Graph

medium

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 value (`int`) and a list (`List[Node]`) of its neighbors.

``` class Node { public int val; public List<Node> neighbors; } ```

The given node will always be the first node with `val = 1`. You must return the copy of the given node as a reference to the cloned graph.

Example 1
Input: adjList = [[2,4],[1,3],[2,4],[1,3]]
Output: [[2,4],[1,3],[2,4],[1,3]]
Explanation: There are 4 nodes in the graph. Node 1's neighbors are nodes 2 and 4. Node 2's neighbors are nodes 1 and 3. The cloned graph has the same structure.
Example 2
Input: adjList = [[]]
Output: [[]]
Explanation: There is one node with no neighbors.
Example 3
Input: adjList = []
Output: []
Explanation: The graph is empty (null node).

Constraints

  • The number of nodes in the graph is in the range [0, 100].
  • 1 <= Node.val <= 100
  • Node.val is unique for each node.
  • There are no repeated edges and no self-loops in the graph.
  • The Graph is connected and all nodes can be visited starting from the given node.
hash-tabledfsbfsgraph
Loading editor...
Test Cases
Click "Run" to execute your code against test cases