Clone Graph

MediumMathLinked ListTreeGraph

Description

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 and a list of its neighbors.

Examples

Input:adjList = [[2,4],[1,3],[2,4],[1,3]]
Output:[[2,4],[1,3],[2,4],[1,3]]
Explanation:

The graph has 4 nodes. Clone each node and its connections.

Input:adjList = [[]]
Output:[[]]
Explanation:

Single node with no neighbors.

Input:adjList = [[2,3],[1,3,4],[1,2,5],[2],[3]]
Output:[[2,3],[1,3,4],[1,2,5],[2],[3]]
Explanation:

The graph has 5 nodes where node 1 connects to nodes 2 and 3, node 2 connects to nodes 1, 3, and 4, node 3 connects to nodes 1, 2, and 5, node 4 connects only to node 2, and node 5 connects only to node 3. This demonstrates cloning a more complex graph with varying degrees of connectivity and leaf nodes.

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.

Ready to solve this problem?

Practice solo or challenge other developers in a real-time coding battle!