forked from neetcode-gh/leetcode
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0261-graph-valid-tree.swift
69 lines (55 loc) · 1.76 KB
/
0261-graph-valid-tree.swift
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
65
66
67
classDisjointSet{
privatevarranks:[Int]
privatevarroots:[Int]
init(numVertices:Int){
ranks =[Int](repeating:0, count: numVertices)
roots =[Int](repeating:0, count: numVertices)
foriin0..<numVertices {
roots[i]= i
ranks[i]=1
}
}
publicfunc union(v1 x:Int, v2 y:Int){
letrootX=find(of: x)
letrootY=find(of: y)
guard rootX != rootY else{return}
letrankX=ranks[rootX]
letrankY=ranks[rootY]
if rankX > rankY { // go into X
roots[rootY]= rootX
}elseif rankY > rankX { // go into Y
roots[rootX]= rootY
}else{ // go into X by default
roots[rootY]= rootX
ranks[rootX]+=1
}
}
privatefunc find(of x:Int)->Int{
ifroots[x]== x {return x }
roots[x]=find(of:roots[x])
returnroots[x]
}
publicfunc areConnected(v1:Int, v2:Int)->Bool{
find(of: v1)==find(of: v2)
}
publicfunc areDisjoint(v1:Int, v2:Int)->Bool{
!areConnected(v1: v1, v2: v2)
}
}
classSolution{
func validTree(_ n:Int, _ edges:[[Int]])->Bool{
// Check if n-1 edges
letnumEdges= edges.count
guard numEdges ==(n -1)else{returnfalse}
// Check if connected => Can use DisjointSet/UnionFind
letds=DisjointSet(numVertices: n)
foredgein edges {
letv1=edge[0]; letv2=edge[1]
guard ds.areDisjoint(v1: v1, v2: v2)else{
returnfalse
}
ds.union(v1: v1, v2: v2)
}
returntrue;
}
}