261. Graph Valid Tree
题目链接:https://leetcode.com/problems...
检查图的连通性及是否有环,可以dfs,bfs,从一个点出发看能不能遍历所有的点,同时visited来检查是否有环。还可以用union find检查是否有环,最后看edge的数量是否等于n-1来判断是不是spinning tree。
public class Solution {
public boolean validTree(int n, int[][] edges) {
if(edges.length != n - 1) return false;
map = new int[n];
Arrays.fill(map, -1);
// union find
for(int[] edge : edges) {
int root1 = find(edge[0]);
int root2 = find(edge[1]);
// if connected before, there is a cycle
if(root1 == root2) return false;
// union
map[root1] = root2;
}
return true;
}
int[] map;
private int find(int child) {
while(map[child] != -1) child = map[child];
return child;
}
}
dfs注意要保留parent指针,这样防止出现u->v之后又返回查一遍
public class Solution {
public boolean validTree(int n, int[][] edges) {
// build graph
build(edges, n);
// store visited node
Set<Integer> visited = new HashSet();
// dfs from 0, to check if visited all nodes and if cycle
if(dfs(visited, 0, -1)) return false;
return visited.size() == n;
}
// adjacent list to represent graph
List<Set<Integer>> graph;
private void build(int[][] edges, int n) {
graph = new ArrayList();
for(int i = 0; i < n; i++) graph.add(new HashSet());
for(int[] edge : edges) {
graph.get(edge[0]).add(edge[1]);
graph.get(edge[1]).add(edge[0]);
}
}
private boolean dfs(Set<Integer> visited, int u, int parent) {
// has cycle
if(visited.contains(u)) return true;
visited.add(u);
for(int v : graph.get(u)) {
if(v == parent) continue;
if(dfs(visited, v, u)) return true;
}
return false;
}
}
bfs同样要要注意避免走重复路经的问题,遍历过的点就删掉。
public class Solution {
public boolean validTree(int n, int[][] edges) {
// build graph
build(edges, n);
// store visited node
Set<Integer> visited = new HashSet();
// bfs from 0, to check if visited all nodes and if cycle
return bfs(visited, n);
}
// adjacent list to represent graph
List<Set<Integer>> graph;
private void build(int[][] edges, int n) {
graph = new ArrayList();
for(int i = 0; i < n; i++) graph.add(new HashSet());
for(int[] edge : edges) {
graph.get(edge[0]).add(edge[1]);
graph.get(edge[1]).add(edge[0]);
}
}
private boolean bfs(Set<Integer> visited, int n) {
Queue<Integer> q = new LinkedList();
q.offer(0);
while(!q.isEmpty()) {
int u = q.poll();
if(visited.contains(u)) return false;
visited.add(u);
for(int v : graph.get(u)) {
q.offer(v);
// remove parent, avoid duplicate
graph.get(v).remove(u);
}
}
return visited.size() == n;
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。