Intuitive Python DFS solution with comments


  • 0
    P

    class Solution:

    def __init__(self):
        self.dict = {}
        
    def cloneGraph(self, node):
        # write your code here
        if node is None:
            return node
        
        if node.label not in self.dict:
            # if the node is not in dict, create the copy in dict first
            n1 = UndirectedGraphNode(node.label)
            self.dict[node.label] = n1
            
            # append all the neighbors by using depth first search. It creates 
            # all the nodes first
            neighbors = []
            for i in node.neighbors:
                neighbors.append(self.cloneGraph(i))
            n1.neighbors = neighbors
            return n1
        else:
            return self.dict[node.label]

Log in to reply
 

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