[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