```
public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
if(node==null) return null;
Set<UndirectedGraphNode> visited = new HashSet<UndirectedGraphNode>();
visited.add(node);
UndirectedGraphNode cloneNode = new UndirectedGraphNode(node.label);
cloneGraph(node,cloneNode,visited);
return cloneNode;
}
private void cloneGraph(UndirectedGraphNode node,UndirectedGraphNode cloneNode,
Set<UndirectedGraphNode> visited){
for(UndirectedGraphNode neighbor: node.neighbors){
if(visited.contains(neighbor)){
return;
}
visited.add(neighbor);
UndirectedGraphNode temp =new UndirectedGraphNode(neighbor.label);
cloneNode.neighbors.add(temp);
cloneGraph(neighbor,temp,visited);
}
return;
}
```