// origin to clone mappingHashMap<Node,Node> oldToNew =newHashMap<>();publicNodecloneGraph(Node node){/*
Idea:
1. A hashmap for old node to new node
2. dfs
3. if the node already in the map, return it
4. Otherwise, copy it and map it
5. gone through each node's neighbours
6. Return the node (Watch out null)
*/// Base caseif(node ==null)returnnull;// Cloned alreadyif(oldToNew.containsKey(node))return oldToNew.get(node);// New node for cloneNode newNode =newNode(node.val,newArrayList<Node>());// Copy it
oldToNew.put(node, newNode);// Iterate through the neighborsfor(Node neighbors : node.neighbors){
newNode.neighbors.add(cloneGraph(neighbors));}return newNode;}