Given n nodes labeled from 0 to n-1 and a list of undirected edges (each edge is a pair of nodes), write a function to check whether these edges make up a valid tree.
class Solution {
public boolean validTree(int n, int[][] edges) {
/*检查一个图是不是树
1.n个点有n-1条边
2.检查连通性,所有点都要连通 via BFS
*/
if(n==0){
return false;
}
if(edges.length!=n-1){
return false;
}
//Establish a graph
Map <Integer, Set<Integer>> graph=initializeGraph(n,edges);
//BFS连通性
Queue <Integer> queue = new LinkedList<>();
Set<Integer> hash = new HashSet<>();//hashset去除重复
queue.offer(0);//起点为0
hash.add(0);//好基友同时操作
while(!queue.isEmpty()){
int node = queue.poll();
//不需要size
//把所有的邻居取出来
for(Integer neighbor : graph.get(node)){
//如果邻居都已经访问过了=在hash里
if(hash.contains(neighbor)){
continue;
}
hash.add(neighbor);//如果不在hash里,添加到里面
queue.offer(neighbor);
}
}
return(hash.size()==n);//queue有增有减,hash一直增加,判断是不是n个点
}
//图的表示 邻接表Map<Integer,Set<Integer>>
//key是一个点,value是邻居
private Map<Integer,Set<Integer>> initializeGraph (int n,int[][] edges){
Map<Integer,Set<Integer>> graph = new HashMap<>();
//初始化
for(int i=0;i<n;i++){
graph.put(i,new HashSet<Integer>());
}
for(int i=0;i<edges.length;i++){
int u =edges[i][0];
int v = edges[i][1];
graph.get(u).add(v);//把v加到u的邻居里面去
graph.get(v).add(u);
}
return graph;
}
}
//int[][] edges 每个边两个点