Taro Logo

Clone Graph

Medium
5 views
2 months ago

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. 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.

For example: 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. 1st node (val = 1)'s neighbors are 2nd node (val = 2) and 4th node (val = 4). 2nd node (val = 2)'s neighbors are 1st node (val = 1) and 3rd node (val = 3). 3rd node (val = 3)'s neighbors are 2nd node (val = 2) and 4th node (val = 4). 4th node (val = 4)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).

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.
Sample Answer
# Definition for a Node.
class Node:
    def __init__(self, val, neighbors):
        self.val = val
        self.neighbors = neighbors

class Solution:
    def cloneGraph(self, node: 'Node') -> 'Node':
        if not node:
            return None

        visited = {}

        def dfs(node):
            if node in visited:
                return visited[node]

            cloned_node = Node(node.val, [])
            visited[node] = cloned_node

            for neighbor in node.neighbors:
                cloned_node.neighbors.append(dfs(neighbor))

            return cloned_node

        return dfs(node)

Explanation:

The problem requires us to create a deep copy of a connected undirected graph. Each node in the graph has a value and a list of neighbors. The goal is to clone the entire graph, such that changes to the original graph do not affect the cloned graph, and vice versa.

  1. Naive Approach (Brute Force):

    • A brute-force approach might involve manually creating new nodes and assigning their values and neighbors based on the original graph. This would be complex and error-prone, especially for larger graphs.
    • It doesn't handle cycles or already visited nodes efficiently.
  2. Optimal Solution (Depth-First Search):

    • The optimal solution uses Depth-First Search (DFS) to traverse the graph and clone each node and its neighbors.
    • A dictionary visited is used to keep track of the cloned nodes to avoid infinite loops in case of cycles and ensure that each node is cloned only once.

Code Implementation:

class Node:
    def __init__(self, val, neighbors):
        self.val = val
        self.neighbors = neighbors

class Solution:
    def cloneGraph(self, node: 'Node') -> 'Node':
        if not node:
            return None

        visited = {}

        def dfs(node):
            if node in visited:
                return visited[node]

            cloned_node = Node(node.val, [])
            visited[node] = cloned_node

            for neighbor in node.neighbors:
                cloned_node.neighbors.append(dfs(neighbor))

            return cloned_node

        return dfs(node)

Walkthrough:

  1. Base Case: If the input node is None, return None.
  2. Visited Dictionary: Initialize a dictionary visited to keep track of cloned nodes.
  3. DFS Function:
    • Check if the current node has already been visited (cloned). If yes, return the cloned node from the visited dictionary.
    • If not visited, create a new node with the same value as the original node.
    • Store the cloned node in the visited dictionary to mark it as visited.
    • Iterate through the neighbors of the original node and recursively call DFS on each neighbor. Append the cloned neighbor to the neighbors list of the cloned node.
    • Return the cloned node.
  4. Return: Call the DFS function with the input node and return the cloned graph.

Big(O) Run-time Analysis:

  • The algorithm visits each node and edge in the graph once.
  • If N is the number of nodes and E is the number of edges, the time complexity is O(N + E).
  • Explanation: DFS traverses all nodes and edges. Each node is visited once, and for each node, we iterate through its neighbors (edges).

Big(O) Space Usage Analysis:

  • The space complexity is O(N), where N is the number of nodes in the graph.
  • Explanation:
    • The visited dictionary stores a clone of each node, which takes O(N) space.
    • The recursion stack of the DFS can go as deep as N in the worst case (e.g., a linked list-like graph), contributing O(N) space.

Edge Cases and Considerations:

  1. Empty Graph: If the input graph is empty (i.e., the input node is None), the function should return None.
  2. Single Node Graph: If the graph contains only one node with no neighbors, the function should create a clone of that node and return it.
  3. Disconnected Graph: The problem statement specifies that the graph is connected. However, if the graph were disconnected, the DFS would only clone the connected component containing the starting node.
  4. Cyclic Graph: The visited dictionary is crucial for handling cyclic graphs. Without it, the algorithm would enter an infinite loop.

By handling these edge cases and using DFS with a visited dictionary, the algorithm correctly clones the graph while avoiding infinite loops and ensuring that each node is cloned only once.