Skip to content

Commit df5c6a1

Browse files
committed
Runtime: 24 ms (Top 15.77%) | Memory: 68.5 MB (Top 7.89%)
1 parent 75a2880 commit df5c6a1

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
// Runtime: 24 ms (Top 15.77%) | Memory: 68.5 MB (Top 7.89%)
2+
class Solution {
3+
int []parent;
4+
int []rank;
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+
public void check(int sr,int sc,int [][]grid){
28+
int mbox=sr*grid[0].length+sc;
29+
for(int i=sr;i<grid.length;i++){
30+
if(grid[i][sc]==1){
31+
int cbox=i*grid[0].length+sc;
32+
int xl=find(mbox);
33+
int yl=find(cbox);
34+
if(xl!=yl){
35+
union(xl,yl);
36+
}
37+
}
38+
}
39+
for(int j=sc;j<grid[0].length;j++){
40+
if(grid[sr][j]==1){
41+
int cbox=sr*grid[0].length+j;
42+
int xl=find(mbox);
43+
int yl=find(cbox);
44+
if(xl!=yl){
45+
union(xl,yl);
46+
}
47+
}
48+
}
49+
}
50+
int find(int x){
51+
if(parent[x]==x){
52+
return x;
53+
}else{
54+
parent[x]=find(parent[x]);
55+
return parent[x];
56+
}
57+
}
58+
void union(int x,int y){
59+
if(rank[x]>rank[y]){
60+
parent[y]=x;
61+
}else if(rank[y]>rank[x]){
62+
parent[x]=y;
63+
}else{
64+
parent[x]=y;
65+
rank[y]++;
66+
}
67+
}
68+
}

0 commit comments

Comments
 (0)