Simple python DFS


  • 0
    S
    # Definition for a undirected graph node
    # class UndirectedGraphNode:
    #     def __init__(self, x):
    #         self.label = x
    #         self.neighbors = []
    
    class Solution:
        # @param node, a undirected graph node
        # @return a undirected graph node
        def __init__(self):
            self.dic = dict() # something to track visited nodes
        
        def cloneGraph(self, node):
            new_node = None
            if node:
                new_node = UndirectedGraphNode(node.label)
                self.dic[node.label] = new_node
                for neighbor in node.neighbors:
                    if neighbor.label in self.dic:
                        new_node.neighbors.append(self.dic[neighbor.label])
                    else:
                        new_node.neighbors.append( self.cloneGraph(neighbor))
            return new_node

Log in to reply
 

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