也是卡了好多天的题目
主要就是介绍了union-find的算法,用于检查Undirected graph有没有环
http://www.geeksforgeeks.org/union-find/
1 public boolean validTree(int n, int[][] edges) { 2 int[] parent = new int[n]; 3 Arrays.fill(parent, -1); 4 for(int i = 0; i < edges.length ; i++) { 5 int x = find(parent, edges[i][0]); 6 int y = find(parent, edges[i][1]); 7 if(x == y) { 8 return false; 9 } 10 parent[x] = y; 11 } 12 return edges.length == n - 1; 13 } 14 15 private int find(int[] parent, int i) { 16 if(parent[i] == -1) { 17 return i; 18 } 19 return find(parent, parent[i]); 20 }
时间: 2024-11-29 06:06:15