Count Servers that Communicate LeetCode solution in Java

1
class Solution {
2
int[] parent;
3
int[] rank;
4

5
public int countServers(int[][] grid) {
6
parent = new int[grid.length * grid[0].length];
7
rank = new int[grid.length * grid[0].length];
8
for (int i = 0; i < parent.length; i++) {
9
parent[i] = i;
10
rank[i] = 0;
11
}
12
for (int i = 0; i < grid.length; i++) {
13
for (int j = 0; j < grid[0].length; j++) {
14
if (grid[i][j] == 1) {
15
check(i, j, grid);
16
}
17
}
18
}
19
int count = 0;
20
for (int i = 0; i < parent.length; i++) {
21
if (parent[i] != i || rank[i] > 0) {
22
count++;
23
}
24
}
25
return count;
26
}
27

28
public void check(int sr, int sc, int[][] grid) {
29
int mbox = sr * grid[0].length + sc;
30
for (int i = sr; i < grid.length; i++) {
31
if (grid[i][sc] == 1) {
32
int cbox = i * grid[0].length + sc;
33
int xl = find(mbox);
34
int yl = find(cbox);
35
if (xl != yl) {
36
union(xl, yl);
37
}
38
}
39
}
40
for (int j = sc; j < grid[0].length; j++) {
41
if (grid[sr][j] == 1) {
42
int cbox = sr * grid[0].length + j;
43
int xl = find(mbox);
44
int yl = find(cbox);
45
if (xl != yl) {
46
union(xl, yl);
47
}
48
}
49
}
50
}
51

52
int find(int x) {
53
if (parent[x] == x) {
54
return x;
55
} else {
56
parent[x] = find(parent[x]);
57
return parent[x];
58
}
59
}
60

61
void union(int x, int y) {
62
if (rank[x] > rank[y]) {
63
parent[y] = x;
64
} else if (rank[y] > rank[x]) {
65
parent[x] = y;
66
} else {
67
parent[x] = y;
68
rank[y]++;
69
}
70
}
71
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0