leetcode16.cloneGraph

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熟练掌握

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值