LeetCode 133. Clone Graph

Post by ailswan Oct.01, 2023

133. Clone Graph

Problem Statement

link: https://leetcode.com/problems/clone-graph/submissions/ https://leetcode.cn/problems/clone-graph/submissions/

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 neighbors; }

Test case format:

For simplicity, each node’s value is the same as the node’s index (1-indexed). For example, the first node with val == 1, the second node with val == 2, and so on. The graph is represented in the test case using an adjacency list.

An adjacency list is a collection of unordered lists used to represent a finite graph. Each list describes the set of neighbors of a node in the graph.

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:

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

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

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

Solution Approach

The solution is based on depth-first traversal where each node’s clone is created recursively ensuring no duplicate clones.

Algorithm

  1. Initialize a dictionary to store visited nodes to avoid cyclic cloning and store clones associated with the original node.
  2. Start the depth-first traversal from the given node. If the node is already visited, return the cloned node from the visited dictionary.
  3. If not visited, create a new clone of the current node, add it to the visited dictionary, and recursively clone all its neighbors. Finally, return the cloned node.

Implement

    class Solution:
  def __init__(self):
      self.visit = {}
      
  def cloneGraph(self, node: Optional['Node']) -> Optional['Node']:
      if not node:
          return node
      if node in self.visit:
          return self.visit[node]
      res = Node(node.val, [])
      self.visit[node] = res
      if node.neighbors:
          res.neighbors = [self.cloneGraph(n) for n in node.neighbors]
      return res