BiruLyu
5/31/2017 - 12:38 AM

## 133. Clone Graph(BFS).java

``````/**
* 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 null;
Map<UndirectedGraphNode, UndirectedGraphNode> map = new HashMap<>();
return dfs(node, map);
}

private UndirectedGraphNode dfs(UndirectedGraphNode node, Map<UndirectedGraphNode, UndirectedGraphNode> map) {
UndirectedGraphNode clone =  map.get(node);
if (clone != null) {
return clone;
}
clone = new UndirectedGraphNode(node.label);
map.put(node, clone);
for (UndirectedGraphNode c : node.neighbors) {
}
return clone;
}
}``````
``````/**
* 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 null;
UndirectedGraphNode newNode = new UndirectedGraphNode(node.label);
HashMap<Integer, UndirectedGraphNode> map = new HashMap<Integer, UndirectedGraphNode>(); //store visited nodes

map.put(newNode.label, newNode);
queue.offer(node);

while(!queue.isEmpty()) {
UndirectedGraphNode cur = queue.poll();

for(UndirectedGraphNode neighbor : cur.neighbors) {
if(!map.containsKey(neighbor.label)) {
map.put(neighbor.label, new UndirectedGraphNode(neighbor.label));