#Problem

#⭐️⭐️⭐️

Graph Valid tree

#Solution

就是找spanning tree的问题. Union Find搞定.

#Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
class Solution {
// A Spanning Tree problem by union find solution
public boolean validTree(int n, int[][] edges) {
// Optimization: a valid tree will have exactly (n - 1) edges connecting n vertices.
if (edges.length != n - 1) return false;
final UnionFind uf = new UnionFind(n);
for (final int[] edge : edges) {
if (uf.find(edge[0], edge[1])) {
return false;
} else {
uf.union(edge[0], edge[1]);
}
}
/*
这里要想清楚两个问题:
1. 最后到底还需不需要判断是否所有结点都connected, 甚至需不需要virtual vertices ?
2. 如果在保证n个结点和n - 1条edge的前提下,还有没有可能在union所有edges之后, 既没有违反规定, 而且还有vertex被拉下的情况 ?
*/
return true;
}
private class UnionFind {
final int[] ids;
final int[] sizes;
final int n;
UnionFind(final int n) {
this.n = n;
this.ids = new int[n];
this.sizes = new int[n];
for (int i = 0; i < n; i++) {
ids[i] = i;
}
}
boolean find(final int v, final int w) {
return root(v) == root(w);
}
void union(final int v, final int w) {
int rootV = root(v);
int rootW = root(w);
if (sizes[rootV] > sizes[rootW]) {
ids[rootW] = rootV;
sizes[rootV] += sizes[rootW];
} else {
ids[rootV] = rootW;
sizes[rootW] += sizes[rootV];
}
}
int root(int id) {
if (id < 0 || id >= n) return -1;
while (ids[id] != id) {
ids[id] = ids[ids[id]];
id = ids[id];
}
return id;
}
}
}

Comments