forked from thuva4/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathunionFind.java
More file actions
37 lines (31 loc) · 731 Bytes
/
unionFind.java
File metadata and controls
37 lines (31 loc) · 731 Bytes
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
//union find algorithm purpose is to find if there is a path between 2 objects or not
public class unionFind {
private int id[];
// constructor takes number of objects
public unionFind(int n) {
id = new int[n];
// set id of each object to itself
for (int i = 0; i < n; i++) {
id[i] = i;
}
}
/**
* connect 2 objects together
*/
public void union(final int n, final int m) {
int nid = id[n];
int mid = id[m];
for (int i = 0; i < id.length; i++) {
if (id[i] == nid) {
id[i] = mid;
}
}
}
/**
* Find whether there is a path between these 2 Objects
*/
public boolean intersected(final int n, final int m) {
// checks if the 2 objects have the same id
return (id[n] == id[m]);
}
}