File tree Expand file tree Collapse file tree 2 files changed +56
-0
lines changed
Expand file tree Collapse file tree 2 files changed +56
-0
lines changed Original file line number Diff line number Diff line change 1+ public interface UF {
2+
3+ int getSize ();
4+
5+ boolean isConnected (int p , int q );
6+
7+ void unionElements (int p , int q );
8+ }
Original file line number Diff line number Diff line change 1+ public class UnionFind1 implements UF {
2+ private int [] id ;
3+
4+ public UnionFind1 (int size ) {
5+ id = new int [size ];
6+ for (int i = 0 ; i < id .length ; i ++) {
7+ id [i ] = i ;
8+ }
9+ }
10+
11+ @ Override
12+ public int getSize () {
13+ return id .length ;
14+ }
15+
16+ // 查找 元素p所对应的集合编号
17+ private int find (int p ) {
18+ if (p < 0 && p >= id .length ) {
19+ throw new IllegalArgumentException ("p is out of bound" );
20+ }
21+ return id [p ];
22+ }
23+
24+
25+ // 查看元素p和元素q是否所属一个集合
26+ @ Override
27+ public boolean isConnected (int p , int q ) {
28+ return find (p ) == find (q );
29+ }
30+
31+ // 合并元素p和元素q所属的集合
32+ @ Override
33+ public void unionElements (int p , int q ) {
34+ int pID = find (p );
35+ int qID = find (q );
36+
37+ if (pID == qID ) {
38+ return ;
39+ }
40+
41+ for (int i = 0 ; i < id .length ; i ++) {
42+ if (id [i ] == pID ) {
43+ id [i ] = qID ;
44+ }
45+ }
46+
47+ }
48+ }
You can’t perform that action at this time.
0 commit comments