java:
package leetcode14.cloneGraph;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.LinkedList;
class UndirectedGraphNode{
int label;
ArrayList<UndirectedGraphNode> neighbors;
UndirectedGraphNode(int x){label=x;neighbors=new ArrayList<UndirectedGraphNode>();}
}
public class Solution {
public UndirectedGraphNode cloneGraph(UndirectedGraphNode node){
if(node==null){
return null;
}
LinkedList<UndirectedGraphNode> queue=new LinkedList<UndirectedGraphNode>();
//the Hashtable's key is the node.the value is the clone node;
Hashtable<UndirectedGraphNode,UndirectedGraphNode> ht=new Hashtable<UndirectedGraphNode,UndirectedGraphNode>();
UndirectedGraphNode root=new UndirectedGraphNode(node.label);//clone the root;
ht.put(node, root);//put into the Hashtable
queue.add(node);//put into the queue
while(!queue.isEmpty()){//BFS begin
UndirectedGraphNode cur=queue.remove();//put out from the queue.get the current node;
UndirectedGraphNode curClone=ht.get(cur);//get the current node's clone node(it must be in the ht)
ArrayList<UndirectedGraphNode> neighbors=cur.neighbors;//get the current node's neighbors
for(int i=0;i<neighbors.size();i++){//neighbors.size() is the arraylist's length
UndirectedGraphNode neighbor=neighbors.get(i);
if(ht.containsKey(neighbor)){//the neighbor has been cloned;
UndirectedGraphNode neighborClone=ht.get(neighbor);//get the neighborClone from the Hashtable (the key is the neighbor)
curClone.neighbors.add(neighborClone);
}else{//the neighbor has not been cloned
UndirectedGraphNode neighborClone = new UndirectedGraphNode(neighbor.label);
curClone.neighbors.add(neighborClone);
ht.put(neighbor, neighborClone);//put into the Hashtable
queue.add(neighbor); //put into the queue
}
}
}
return root;
}
}
总结:BFS的使用,使用queue作为数据结构~ 应和DFS熟练掌握