[Leetcode] Clone Graph (python), leetcodepython

Source: Internet
Author: User

[Leetcode] Clone Graph (python), leetcodepython

Similar to the three types of traversal of Binary trees, we can do a lot of additional things based on the traversal template. The two types of graph traversal, depth and breadth templates can also do a lot of additional things, here, we use templates with deep priority traversal for replication. In depth precedence, we first access the first node and then the first adjacent node, and then access the neighboring node of the neighboring node ....

Class Solution: # @ param node, a undirected graph node # @ return a undirected graph node def cloneGraph (self, node): if None = node: return None nodeMap = {} return self. cloneNode (node, nodeMap) def cloneNode (self, node, nodeMap): if None = node: return None # access the current vertex. This is not a simple print, but a copy, if the node has been copied, if nodeMap is returned. has_key (node): return nodeMap [node] # if there is no copy, copy one copy and process the adjacent node else: clone = UndirectedGraphNode (node. label) nodeMap [node] = clone # access the neighbor node for neighbor in node. neighbors: clone. neighbors. append (self. cloneNode (neighbor, nodeMap) return clone

Similar to this question,

If additional space is allowed in the Copy List with Random Pointer question, we can also use this method to obtain a Copy.

class Solution:    # @param head, a RandomListNode    # @return a RandomListNode    def copyRandomList(self, head):        if None == head: return None        nodeMap = {}        return self.copyListNode(head, nodeMap)            def copyListNode(self, node, nodeMap):        if None == node: return None        if nodeMap.has_key(node):            return nodeMap[node]        else:             cpNode = RandomListNode(node.label)            nodeMap[node] = cpNode            cpNode.next = self.copyListNode(node.next, nodeMap)            cpNode.random = self.copyListNode(node.random, nodeMap)        return cpNode 





Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.