class Solution:
di = {}
def cloneGraph(self, node):
if node == None:
return node
if node.label in self.di:
return self.di[node.label]
self.di[node.label] = UndirectedGraphNode(node.label)
self.di[node.label].neighbors = [self.cloneGraph(n) for n in node.neighbors]
return self.di[node.label]
[Python] I can't find anything wrong with this solution, yet it fails.


you should declare another member function and do like this:
class Solution: di = {} def cloneGraphRec(self, node): if node == None: return node if node.label in self.di: return self.di[node.label] self.di[node.label] = UndirectedGraphNode(node.label) self.di[node.label].neighbors = [self.cloneGraphRec(n) for n in node.neighbors] return self.di[node.label] def cloneGraph(self, node): di = {} return self.cloneGraphRec(node)

You can do like this as well:
def __init__(self): self.di = {} def cloneGraph(self, node): if node == None: return node if node.label in self.di: return self.di[node.label] self.di[node.label] = UndirectedGraphNode(node.label) self.di[node.label].neighbors = [self.cloneGraph(n) for n in node.neighbors] return self.di[node.label]