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 资源

通过相关的交互式教程、备忘单和代码比较来扩展您的知识。