AlgoMaster Logo

Clone Graph

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Depth-First Search (DFS)

Intuition:

The DFS approach involves recursively creating clone nodes and copying the connections (neighbors) in a depth-first manner. We use a hashmap to store the node's original as a key and its clone as a value to avoid creating multiple copies of the same node.

Steps:

  1. A base case checks if the input node is null, returning null if true.
  2. If the node has already been cloned (exists in the hashmap), return the cloned node.
  3. Initiate a clone node and store it in the hashmap.
  4. Recursively visit each neighbor of the node and add the cloned neighbors to the clone node's neighbors list.
  5. Return the cloned node.

Code:

2. Breadth-First Search (BFS)

Intuition:

This approach consists of a breadth-first traversal using a queue. It uses a hashmap to store cloned nodes and iteratively connects neighbors by dequeuing nodes and exploring their neighbors.

Steps:

  1. Handle the base case where input node is null by returning null.
  2. Use a hashmap to store visited and cloned nodes.
  3. Initialize a queue with the original node and clone the root node.
  4. While the queue is not empty, process the node:
    • For each neighbor, if not cloned, clone and enqueue it.
    • Update the current node's clone to include the clone of its neighbors.
  5. Once traversal ends, return the clone of the original node.

Code: