-
Notifications
You must be signed in to change notification settings - Fork 211
Expand file tree
/
Copy pathUFSearch.java
More file actions
executable file
·67 lines (62 loc) · 1.55 KB
/
UFSearch.java
File metadata and controls
executable file
·67 lines (62 loc) · 1.55 KB
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
package ca.mcmaster.chapter.four.graph;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class UFSearch extends AbstractSearch {
private final UF uf;
public UFSearch(Graph g, int s) {
super(g, s);
this.uf = new UF(g.V());
//Insert connections into the UF.
for(int v = 0; v < g.V(); v++){
for(int w : g.adj(v)){
if(uf.connected(v, w)) continue;
else uf.union(v, w);
}
}
}
@Override
public boolean mark(int v) {
return uf.connected(super.s, v);
}
@Override
public int count() {
return uf.size[super.s];
}
private final class UF{
private final int N;
private final int[] a;
private final int[] size;
public UF(int N){
this.N = N;
a = new int[N];
for(int i = 0; i < N; i++) a[i] = i;
size = new int[N];
for(int i = 0; i < N; i++) size[i] = 1;
}
public int find(int v){
if(a[v] == v) return v;
else return find(a[v]);
}
public void union(int p, int q){
int qRoot = find(q);
int pRoot = find(p);
if(pRoot == qRoot) return;
if(size[qRoot] < size[pRoot]){
a[qRoot] = pRoot;
size[pRoot] += size[qRoot];
}else{ //size[qRoot] >= size[pRoot]
a[pRoot] = qRoot;
size[qRoot] += size[pRoot];
}
}
public boolean connected(int p, int q){
return find(q) == find(p);
}
}
public static void main(String[] args) throws FileNotFoundException {
Graph g = new UndirectedGraph(new FileInputStream(new File("src/ca/mcmaster/chapter/four/graph/tinyG.txt")));
Search search = new UFSearch(g, 9);
System.out.println(search.mark(4));
}
}