[LeetCode] #133. Clone Graph
題目 Given a reference of a node in a connected undirected graph. Return a deep copy (clone) of the graph. Each node in the graph contains a value (int) and a list (List[Node]) of its neighbors. 直覺解 構想: 用 dictionary 儲存已經複製好的節點,因為節點的 val 和節點的編號是一樣的,所以就用 val 的值當作 key。用 waiting_stack 儲存待複製的節點。 while 迴圈:從 waiting_stack 裡拿出節點,先複製這個節點。然後迭代該節點的鄰居,把鄰居複製一份,把複製的鄰居 append 到 neighbors 裡;因為鄰居的鄰居還沒有被複製,所以需要把鄰居放進去 waiting_stack。 python 3 實作: def cloneGraph(self, node: 'Node') -> 'Node': if not node: return None def clone_node(node): if not clonedNodes.get(node.val): clonedNodes[node.val] = Node(node.val) return clonedNodes[node.val] clonedNodes = {} waiting_stack = [node] while waiting_stack: current = waiting_s...