題目出處
難度
medium
個人範例程式碼
"""
# Definition for a Node.
class Node:
def __init__(self, val = 0, neighbors = None):
self.val = val
self.neighbors = neighbors if neighbors is not None else []
"""
class Solution:
def cloneGraph(self, node: 'Node') -> 'Node':
root = node
if node is None:
return node
# traverse, get all nodes by BFS
old_nodes = self.get_all_nodes(node)
# print(len(nodes))
# clone all nodes
mapping = {}
for old_node in old_nodes:
mapping[old_node] = Node(old_node.val)
# clone all edges
for old_node in old_nodes: #
new_node = mapping[old_node]
for neighbor in old_node.neighbors:
new_neighbor = mapping[neighbor]
new_node.neighbors.append(new_neighbor)
return mapping[root]
def get_all_nodes(self, node):
queue = [node]
result = set([node])
while queue:
head = queue.pop(0)
for neighbor in head.neighbors:
if neighbor not in result:
result.add(neighbor)
queue.append(neighbor)
return result
算法說明
不好處理的題目,題目本身不難,但基本上可以視為 Graph 的基本操作題型。
我們分成三大步驟
- - 找到所有的點,透過 BFS traverse
- 複製所有的點
- 複製所有的邊
最近在練習程式碼本身就可以自解釋的 Coding style,可以嘗試直接閱讀程式碼理解
input handling
處理 input 為空的情況,這裡我是直接回傳 node。
Boundary conditions
注意 BFS 的結束條件:
- 當 queue 為空,所有的點都為 visited