I get a similar error with a different root cause compared to: Clone Graph LeetCode 133
Consider the below implementation. If I use a Node-type key for processed_node_map
, the algorithm passes. If I use node.val
as the key, I receive the error:
Node with value 2 doesn't exist in the original graph.
Question: Can anyone explain why this error is occurring? TYIA
Constraints and notes:
- Node.val is constrained to be unique across nodes in the input.
- This error is seen in a test case with no input value of 2.
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
processed_node_map = {}
class Solution:
# solution: https://leetcode.com/problems/clone-graph/solutions/5092202/blind-75-beats-88-06-46-75/
def cloneGraph(self, node: Optional['Node']) -> Optional['Node']:
return self.dfs(node) if node else None
def dfs(self, node):
if node.val in processed_node_map:
return processed_node_map[node.val]
clone = Node(val=node.val)
processed_node_map[node.val] = clone
calculated_neighbors = []
for child in node.neighbors:
calculated_neighbors.append(self.dfs(child))
clone.neighbors = calculated_neighbors
return clone