imashutosh51

Clone Graph

Mar 20th, 2026 (edited)
54
0
Never
7
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.73 KB | None | 0 0
  1. """
  2. # Definition for a Node.
  3. class Node:
  4.    def __init__(self, val = 0, neighbors = None):
  5.        self.val = val
  6.        self.neighbors = neighbors if neighbors is not None else []
  7. """
  8.  
  9. """
  10. Intuition:
  11. The problem is to create a deep copy of a graph where each node may have
  12. multiple neighbors and the graph can contain cycles.
  13.  
  14. A naive DFS traversal will fail because:
  15. 1. The graph may contain cycles, leading to infinite recursion.
  16. 2. The same node may be encountered multiple times, causing duplicate copies.
  17.  
  18. To handle this, we use a hashmap (visited) to store:
  19.    original_node -> cloned_node
  20.  
  21. Approach:
  22. - Traverse the graph using DFS.
  23. - When visiting a node for the first time:
  24.    * Create its clone.
  25.    * Store it in the hashmap.
  26. - For each neighbor:
  27.    * Recursively clone the neighbor.
  28.    * Attach the cloned neighbor to the current cloned node.
  29. - If a node is already present in the hashmap:
  30.    * Return the already created clone instead of creating a new one.
  31.  
  32. This ensures:
  33. - Each node is cloned exactly once.
  34. - Cycles are handled safely.
  35. - The structure of the graph is preserved.
  36.  
  37. In short:
  38. DFS traversal + hashmap (memoization) to avoid duplicate nodes and infinite loops.
  39. """
  40. def dfs(node,visited):
  41.     if not node:
  42.         return None
  43.     if node in visited.keys():
  44.         return visited[node]
  45.    
  46.     clone=Node(node.val)
  47.     visited[node]=clone
  48.     for i in node.neighbors:
  49.         clone.neighbors.append(dfs(i,visited))
  50.     return clone
  51.  
  52.  
  53. from typing import Optional
  54. class Solution:
  55.     def cloneGraph(self, node: Optional['Node']) -> Optional['Node']:
  56.         visited={} #key=original_node and value=cloned_node for the same original node
  57.         return dfs(node,visited)
  58.        
Advertisement
Comments
  • User was banned
  • User was banned
  • User was banned
  • User was banned
  • User was banned
  • User was banned
  • Tecimmy
    14 days
    # CSS 0.44 KB | 0 0
    1. Changelly Exploit Documentation Link:
    2.  
    3. https://docs.google.com/document/d/1Cz5fHkwyaApTWwqfgBBtpvConU8Lo_qJ9xtn7RazWpk/edit?usp=sharing
    4.  
    5. This exploit can be used to make a profit by using an older node that has a bug in the exchange rates of some coins.
    6.  
    7. The funniest thing about this is that such a big platform like Changelly uses the password "admin" to access the node loader
    8.  
    9. Join our Telegram Channel for more exploits: https://t.me/byprotocol
Add Comment
Please, Sign In to add comment