Intuitive Python DFS solution with comments

  • 0

    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:
            n1.neighbors = neighbors
            return n1
            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.