BFS:
public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
if (node == null) {
return null;
}
Queue<UndirectedGraphNode> queue = new LinkedList<UndirectedGraphNode>();
queue.offer(node);
Map<UndirectedGraphNode,UndirectedGraphNode> map = new HashMap<UndirectedGraphNode, UndirectedGraphNode>();
UndirectedGraphNode newNode = new UndirectedGraphNode(node.label);
map.put(node, newNode);
while (!queue.isEmpty()) {
UndirectedGraphNode tmp = queue.poll();
for (UndirectedGraphNode neighbor : tmp.neighbors) {
if (map.get(neighbor) == null) {
UndirectedGraphNode newNeighbor = new UndirectedGraphNode(neighbor.label);
map.put(neighbor, newNeighbor);
queue.offer(neighbor);
}
map.get(tmp).neighbors.add(map.get(neighbor));
}
}
return newNode;
}
public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
if (node == null) {
return null;
}
Queue<UndirectedGraphNode> queue = new LinkedList<UndirectedGraphNode>();
Map<UndirectedGraphNode, UndirectedGraphNode> map = new HashMap<UndirectedGraphNode, UndirectedGraphNode>();
queue.offer(node);
while (!queue.isEmpty()) {
UndirectedGraphNode cur = queue.poll();
if (map.get(cur) == null) {
UndirectedGraphNode newNode = new UndirectedGraphNode(cur.label);
map.put(cur, newNode);
for (UndirectedGraphNode neighbor : cur.neighbors) {
queue.offer(neighbor);
}
}
}
for (UndirectedGraphNode cur : map.keySet()) {
for (UndirectedGraphNode neighbor : cur.neighbors) {
map.get(cur).neighbors.add(map.get(neighbor));
}
}
return map.get(node);
}
DFS:
public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
if (node == null) {
return null;
}
Map<UndirectedGraphNode,UndirectedGraphNode> map = new HashMap<UndirectedGraphNode, UndirectedGraphNode>();
UndirectedGraphNode newNode = new UndirectedGraphNode(node.label);
map.put(node, newNode);
dfs(node, map);
return newNode;
}
void dfs(UndirectedGraphNode root, Map<UndirectedGraphNode,UndirectedGraphNode> map) {
UndirectedGraphNode newNode = map.get(root);
for (UndirectedGraphNode neighbor : root.neighbors) {
if (map.get(neighbor) == null) {
UndirectedGraphNode newNeighbor = new UndirectedGraphNode(neighbor.label);
map.put(neighbor, newNeighbor);
dfs(neighbor, map);
}
newNode.neighbors.add(map.get(neighbor));
}
}