Description:
Given a reference of a node in a connected undirected graph.
Return a deep copy (clone) of the graph.
Each node in the graph contains a value (int
) and a list (List[Node]
) of its neighbors.
class Node {
public int val;
public List<Node> neighbors;
}
Test case format:
For simplicity, each node’s value is the same as the node’s index (1-indexed). For example, the first node with val == 1
, the second node with val == 2
, and so on. The graph is represented in the test case using an adjacency list.
An adjacency list is a collection of unordered lists used to represent a finite graph. Each list describes the set of neighbors of a node in the graph.
The given node will always be the first node with val = 1
. You must return the copy of the given node as a reference to the cloned graph.
Examples:
Example 1:
Input: adjList = [[2,4],[1,3],[2,4],[1,3]]
Output: [[2,4],[1,3],[2,4],[1,3]]
Explanation: There are 4 nodes in the graph.
1st node (val = 1)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).
2nd node (val = 2)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).
3rd node (val = 3)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).
4th node (val = 4)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).
Example 2:
Input: adjList = [[]]
Output: [[]]
Explanation: Note that the input contains one empty list. The graph consists of only one node with val = 1 and it does not have any neighbors.
Example 3:
Input: adjList = []
Output: []
Explanation: This an empty graph, it does not have any nodes.
Solution in Python:
Approach
- Node Class Definition: Ensure we have the correct
Node
class definition. - HashMap for Visited Nodes: Use a hashmap (dictionary) to map original nodes to their corresponding copied nodes.
- DFS for Cloning: Perform a DFS to clone each node and its neighbors recursively.
Steps
- Base Case: If the input node is
None
, returnNone
. - Check Visited: If the node has already been copied (i.e., it is in the hashmap), return the copied node from the hashmap.
- Clone the Node: Create a copy of the current node.
- Store the Copied Node: Add the copied node to the hashmap.
- Clone Neighbors: Recursively clone all neighbors of the current node and add them to the neighbors list of the copied node.
# 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 []
from typing import Optional, Dict
class Solution:
def cloneGraph(self, node: Optional['Node']) -> Optional['Node']:
if not node:
return None
# Dictionary to keep track of copied nodes
visited: Dict[Node, Node] = {}
def dfs(node: 'Node') -> 'Node':
if node in visited:
return visited[node]
# Create a copy of the node
copy = Node(node.val)
visited[node] = copy
# Recursively copy all the neighbors
for neighbor in node.neighbors:
copy.neighbors.append(dfs(neighbor))
return copy
return dfs(node)
Explanation
- Node Class Definition: The
Node
class has been defined as per the requirement. - Base Case: If the input
node
isNone
, the function immediately returnsNone
. - Check Visited: Before cloning a node, the function checks if it has already been cloned using the
visited
dictionary. - Clone the Node: If the node hasn’t been cloned, a new node is created and stored in the
visited
dictionary. - Clone Neighbors: The function then recursively clones all neighbors of the current node and appends them to the neighbors list of the copied node.
This approach ensures that each node is cloned exactly once and that all references between nodes are correctly maintained in the copied graph.
Solution in Javascript:
/**
* @param {_Node} node
* @return {_Node}
*/
var cloneGraph = function(node) {
// Base case: If the input node is null, return null
if (node === null) {
return null;
}
// Hashmap to keep track of visited nodes
const visited = new Map();
// Helper function to perform DFS
const dfs = (node) => {
// If the node has already been visited, return the cloned node
if (visited.has(node)) {
return visited.get(node);
}
// Create a copy of the current node
const copy = new _Node(node.val);
// Store the copy in the hashmap
visited.set(node, copy);
// Recursively clone all the neighbors
for (let neighbor of node.neighbors) {
copy.neighbors.push(dfs(neighbor));
}
return copy;
};
// Start DFS from the given node
return dfs(node);
};
Solution in Java:
import java.util.HashMap;
import java.util.Map;
public class Solution {
public Node cloneGraph(Node node) {
// Base case: If the input node is null, return null
if (node == null) {
return null;
}
// HashMap to keep track of visited nodes
Map<Node, Node> visited = new HashMap<>();
// Helper function to perform DFS
return dfs(node, visited);
}
private Node dfs(Node node, Map<Node, Node> visited) {
// If the node has already been visited, return the cloned node
if (visited.containsKey(node)) {
return visited.get(node);
}
// Create a copy of the current node
Node copy = new Node(node.val);
// Store the copy in the HashMap
visited.put(node, copy);
// Recursively clone all the neighbors
for (Node neighbor : node.neighbors) {
copy.neighbors.add(dfs(neighbor, visited));
}
return copy;
}
}
Solution in C#:
using System;
using System.Collections.Generic;
public class Solution {
public Node CloneGraph(Node node) {
// Base case: If the input node is null, return null
if (node == null) {
return null;
}
// Dictionary to keep track of visited nodes
Dictionary<Node, Node> visited = new Dictionary<Node, Node>();
// Helper function to perform DFS
Node dfs(Node n) {
// If the node has already been visited, return the cloned node
if (visited.ContainsKey(n)) {
return visited[n];
}
// Create a copy of the current node
Node copy = new Node(n.val);
// Store the copy in the dictionary
visited[n] = copy;
// Recursively clone all the neighbors
foreach (Node neighbor in n.neighbors) {
copy.neighbors.Add(dfs(neighbor));
}
return copy;
}
// Start DFS from the given node
return dfs(node);
}
}