150強訪談中等

複製圖

“克隆圖”問題的詳細指南和 Python 實作。

問題陳述

中等

給定連接無向圖中節點的引用,傳回該圖的深層副本(克隆)。

圖中的每個節點都包含一個值 (int) 及其鄰居清單 (List[Node])。

此圖表示為鄰接表。實作函數 cloneGraph(adjList: List[List[int]]) -> List[List[int]] ,其中 adjList[i] 表示節點 i+1 的鄰居(1 索引)。傳回克隆圖的鄰接表。

約束條件
  • The number of nodes in the graph is in the range [0, 100]
  • 1 <= Node.val <= 100
  • Node.val is unique for each node
  • There are no repeated edges and no self-loops in the graph

範例

Example 1
Input
adjList = [[2,4],[1,3],[2,4],[1,3]]
Output
[[2,4],[1,3],[2,4],[1,3]]
Explanation

Node 1's neighbors are 2 and 4. Node 2's neighbors are 1 and 3. Node 3's neighbors are 2 and 4. Node 4's neighbors are 1 and 3.

Example 2
Input
adjList = [[]]
Output
[[]]
Explanation

The graph contains only one node with value 1 and no neighbors.

Need a Hint?
考慮使用特定於圖的資料結構,例如集合或堆。
Edge Cases to Watch
  • 空輸入結構
  • 單元素輸入
  • 大數值範圍

準備好解決了嗎?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在編輯器中開啟
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推薦的 Python 資源

透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。