1class Solution {
2 private Map<Node, Node> visited = new HashMap<>();
3
4 public Node cloneGraph(Node node) {
5 // Base case
6 if (node == null) {
7 return null;
8 }
9
10 // If the node was already visited, return the clone from the hashmap
11 if (visited.containsKey(node)) {
12 return visited.get(node);
13 }
14
15 // Create a clone for the node
16 Node cloneNode = new Node(node.val);
17 visited.put(node, cloneNode);
18
19 // Iterate over the neighbors to populate the cloned graph
20 for (Node neighbor : node.neighbors) {
21 cloneNode.neighbors.add(cloneGraph(neighbor));
22 }
23 return cloneNode;
24 }
25}