Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors.
分析:
广度优先遍历,涉及队列的应用,
节点有没有访问过的标记,HashMap的应用。
/**
* 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;
//广度优先遍历的常规技术,利用队列
Queue<UndirectedGraphNode> queue = new LinkedList<UndirectedGraphNode>();
//HashMap用来标记节点有没有访问过
HashMap<UndirectedGraphNode,UndirectedGraphNode> hashMap = new HashMap<UndirectedGraphNode,UndirectedGraphNode>();
//先把第一个节点放进队列,完成初始化
queue.add(node);
UndirectedGraphNode clone = new UndirectedGraphNode(node.label);
hashMap.put(node, clone);
//开始遍历
while(!queue.isEmpty()){
UndirectedGraphNode curr = queue.remove();
UndirectedGraphNode currClone = hashMap.get(curr);
//对于当前节点的邻居
for(UndirectedGraphNode item : curr.neighbors){
//如果在hashMap里,说明已经访问过,建立指针关系即可
if(hashMap.containsKey(item)){
currClone.neighbors.add(hashMap.get(item));
}else{//如果没有在hashMap里,说明没有访问过,除了新建节点并建立指针关系外,
//还要再hashMap里放入新对,并将没有访问过的节点入队
UndirectedGraphNode newItem = new UndirectedGraphNode(item.label);
currClone.neighbors.add(newItem);
hashMap.put(item, newItem);
queue.add(item);
}
}
}
return clone;
}
}