Clone Graph
LeetCode 133 · ಮಧ್ಯಮ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್ಥ್ರೂ
original → copy map as both cache and visited set.
ನಾನು 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
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.
ನಾನು ಹೇಗೆ ಪರಿಹರಿಸಿದೆ
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.