Tensorum
YouTubeகற்கத் தொடங்குங்கள்
LeetCode 133 · Graph Fundamentals / BFS

Clone Graph

LeetCode 133 · நடுத்தரம் · தீர்வு, intuition & படிப்படியான வாக்த்ரூ

original → copy map as both cache and visited set.

நடுத்தரம்Hash TableDepth-First SearchBreadth-First SearchGraph Theory
LeetCode இல் திற ↗

நான் Clone Graph (LeetCode 133) ஐ இப்படித் தீர்த்தேன் — Graph Fundamentals / BFS பேட்டர்னின் ஒரு நடுத்தரம் பிராப்ளம். கீழே: intuition, படிப்படியான approach, என் accepted Python கோட், animated test cases மற்றும் line-by-line debugger.

கீழேயுள்ள விளக்கம் ஆங்கிலத்தில் உள்ளது.

Intuition

DFS through the graph and keep a map from each original node to its copy. The map doubles as the visited set: if a node already has a copy, reuse it — that's how cycles are handled.

Approach

  1. 1

    dfs(node): if copied already, return the copy.

  2. 2

    Create the copy and store it before visiting neighbours.

  3. 3

    Append dfs(neighbour) for every neighbour.

நான் எப்படித் தீர்த்தேன்

DFS with copy mapPythonO(V+E) time
"""
# Definition for a Node.
class Node:
    def __init__(self, val = 0, neighbors = None):
        self.val = val
        self.neighbors = neighbors if neighbors is not None else []
"""

from typing import Optional
class Solution:
    def cloneGraph(self, node: Optional['Node']) -> Optional['Node']:
        """
        make a hashmap to keep the node and it's value
        we can maintain same map as visited as well as to keep the copy
        """
        visited_mpp = {}
        def dfs(node):
            nonlocal visited_mpp
            if node in visited_mpp:
                #simply return the copy
                return visited_mpp[node]
            else:
                copy = Node(node.val)
                visited_mpp[node]=copy
                for adj_node in node.neighbors:
                    copy.neighbors.append(dfs(adj_node))
                return copy
        return dfs(node) if node is not None else None
ஸ்டெப்-த்ரூ ஏற்றுகிறது…

Clone Graph — அடிக்கடி கேட்கப்படும் கேள்விகள்

Clone Graph பின்னாலுள்ள intuition என்ன?

DFS through the graph and keep a map from each original node to its copy. The map doubles as the visited set: if a node already has a copy, reuse it — that's how cycles are handled.

Clone Graph (LeetCode 133) ஐ எப்படித் தீர்ப்பது?

1. dfs(node): if copied already, return the copy. 2. Create the copy and store it before visiting neighbours. 3. Append dfs(neighbour) for every neighbour.

Clone Graph இன் time மற்றும் space complexity என்ன?

Time: O(V + E). Space: O(V). (Accepted approach: DFS with copy map.)

Clone Graph இல் பொதுவான தவறுகள் என்ன?

Store the copy before recursing, or cycles loop forever.