Graph Valid Tree
public class Solution {
/**
* @param n: An integer
* @param edges: a list of undirected edges
* @return: true if it's a valid tree, or false
*/
public boolean validTree(int n, int[][] edges) {
if (n == 0) return false;
if (edges.length != n - 1) return false;//edge + 1 = n Valid Tree 的必要条件_套路
Map<Integer, Set<Integer>> graph = initGraph(n, edges);
Queue<Integer> queue = new LinkedList<Integer>();
Set<Integer> hash = new HashSet<>();
queue.offer(0);
hash.add(0);
while (!queue.isEmpty()) {
int cur = queue.poll();
for (int nei : graph.get(cur)) {
if (!hash.contains(nei)) {
queue.offer(nei);
hash.add(nei); //BFS套路
}
}
}
return hash.size() == n;
}
//HashMap<key-node, value-connected nodes>
private Map<Integer, Set<Integer>> initGraph(int n, int[][] edges) {
Map<Integer, Set<Integer>> graph = new HashMap<Integer, Set<Integer>>();
for (int i = 0; i < n; i++) {
graph.put(i, new HashSet<Integer>()); //用节点关系建立graph
}
for (int j = 0; j < edges.length; j++) {
int u = edges[j][0];
int v = edges[j][1];
graph.get(u).add(v);
graph.get(v).add(u); // graph.add(graph.get(v), u);这里为什么不对??
}
return graph;
}
}
最后更新于
这有帮助吗?