/**
* Definition for undirected graph.
* class UndirectedGraphNode {
* int label;
* List<UndirectedGraphNode> neighbors;
* UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<UndirectedGraphNode>(); }
* };
*/
public class Solution {
public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
if (node == null) {
return node;
}
HashMap<UndirectedGraphNode, UndirectedGraphNode> map = new HashMap<UndirectedGraphNode, UndirectedGraphNode>();
return dfs(node, map);
}
private UndirectedGraphNode dfs(UndirectedGraphNode node, HashMap<UndirectedGraphNode, UndirectedGraphNode> map) {
if (map.containsKey(node)) {
return map.get(node);
}
UndirectedGraphNode copyNode = new UndirectedGraphNode(node.label);
map.put(node, copyNode);
for (UndirectedGraphNode neighborNode : node.neighbors) {
copyNode.neighbors.add(dfs(neighborNode, map));
}
return copyNode;
}
}