看不懂啊看不懂啊看不懂啊
等爷晚上再写吧
题目
https://leetcode-cn.com/problems/regions-cut-by-slashes/
分析
代码
class Solution {
public int regionsBySlashes(String[] grid) {
int len = grid.length;
Union uf = new Union(4*len*len);
for(int i=0;i<len;i++){
for(int j=0;j<len;j++){
int index = 4*(i*len+j);
switch(grid[i].charAt(j)){
//当字符为‘ ’时,小方块 4 个区域全部合并
case' ':
uf.union(index,index+1);
uf.union(index+2,index+3);
uf.union(index,index+2);
break;
//当字符为‘/’时,那么小方块的 0,3 区域合并,1,2 区域合并
case'/':
uf.union(index,index+3);
uf.union(index+1,index+2);
break;
//当字符为‘\\’时 ,小方块的 0,1 区域合并,2,3 区域合并
case'\\':
uf.union(index,index+1);
uf.union(index+2,index+3);
break;
}
//考虑特殊情况
//如果当前行数大于0,那么该方块的 0 区域就可以与上一行同一列小方块的 2 区域合并;
//如果当前列数大于0,那么该方块的 3 区域就可以与上一列同一行小方块的 1 区域合并;
if(i>0){
uf.union(index,index-4*len+2);
}
if(j>0){
uf.union(index+3,index-3);
}
}
}
return uf.count();
}
}
class Union {
int parent[];
int size[];
int count;
public Union(int n){
parent = new int[n];
size = new int[n];
count = n;
for(int i=0;i<n;i++){
parent[i] = i;
size[i] = 1;
}
}
public void union(int index1,int index2){
int root1 = find(index1);
int root2 = find(index2);
if(root1==root2){
return;
}
if(size[root1]>size[root2]){
parent[root2] = root1;
size[root1] += size[root2];
} else {
parent[root1] = root2;
size[root2] += size[root1];
}
count--;
}
public int find(int index){
while(index!=parent[index]){
parent[index] = parent[parent[index]];
index = parent[index];
}
return index;
}
public int count(){
return count;
}
}