[Python] I can't find anything wrong with this solution, yet it fails.


  • 0
    S
    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]

  • 0
    J

    di is not clear after each test


  • 1
    V

    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)

  • 0
    C

    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]

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.