Python DFS


  • 0
    D
    class Solution:
        def cloneGraph(self, node):
            if not node:
                return None
            visited = set()
            val2node = {node.label: UndirectedGraphNode(node.label)}
            self.dfs(node, visited, val2node)
            return val2node[node.label]
    
        def dfs(self, node, visited, val2node):
            if node.label in visited:
                return
            visited.add(node.label)
            dup = val2node[node.label]
            for child in node.neighbors:
                if child.label not in val2node:
                    val2node[child.label] = UndirectedGraphNode(child.label)
                dup.neighbors.append(val2node[child.label])
                self.dfs(child, visited, val2node)
    

Log in to reply
 

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