Le migliori 150 intervisteMedio

Clona grafico

Guida dettagliata e implementazione Python per il problema "Clone Graph".

Dichiarazione del problema

Medio

Dato un riferimento di un nodo in un grafo non orientato connesso, restituisce una copia profonda (clone) del grafo.

Ogni nodo nel grafico contiene un valore (int) e un elenco dei suoi vicini (Lista[Nodo]).

Il grafico è rappresentato come una lista di adiacenze. Implementare una funzione cloneGraph(adjList: List[List[int]]) -> List[List[int]] dove adjList[i] rappresenta i vicini del nodo i+1 (indicizzato in 1). Restituisce la lista delle adiacenze del grafo clonato.

Vincoli
  • 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

Esempi

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?
Prendi in considerazione l'utilizzo di strutture dati specifiche di Graphs come set o heap.
Edge Cases to Watch
  • Strutture di input vuote
  • Ingressi a elemento singolo
  • Grandi limiti numerici

Pronto a risolvere?

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

Apri nell'editor
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

Risorse Python consigliate

Espandi le tue conoscenze con tutorial interattivi, foglietti illustrativi e confronti di codici correlati.