Top 150-InterviewMittel

Diagramm klonen

Detaillierte Anleitung und Python-Implementierung für das Problem „Clone Graph“.

Problemstellung

Mittel

Geben Sie bei einer Referenz eines Knotens in einem verbundenen ungerichteten Diagramm eine tiefe Kopie (Klon) des Diagramms zurück.

Jeder Knoten im Diagramm enthält einen Wert (int) und eine Liste seiner Nachbarn (List[Node]).

Der Graph wird als Adjazenzliste dargestellt. Implementieren Sie eine Funktion cloneGraph(adjList: List[List[int]]) -> List[List[int]], wobei adjList[i] die Nachbarn von Knoten i+1 (1-indiziert) darstellt. Gibt die Adjazenzliste des geklonten Diagramms zurück.

Einschränkungen
  • 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

Beispiele

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?
Erwägen Sie die Verwendung von Graphs-spezifischen Datenstrukturen wie Mengen oder Heaps.
Edge Cases to Watch
  • Leere Eingabestrukturen
  • Einzelelementeingaben
  • Große numerische Grenzen

Bereit zur Lösung?

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

Im Editor öffnen
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

Empfohlene Python-Ressourcen

Erweitern Sie Ihr Wissen mit zugehörigen interaktiven Tutorials, Spickzetteln und Codevergleichen.