package com.heu.wsq.leetcode.bingchaji;
/**
* 959. 由斜杠划分区域
* @author wsq
* @date 2021/1/25
* 在由 1 x 1 方格组成的 N x N 网格 grid 中,每个 1 x 1 方块由 /、\ 或空格构成。这些字符会将方块划分为一些共边的区域。
* (请注意,反斜杠字符是转义的,因此 \ 用 "\\" 表示。)。
* 返回区域的数目。
*
* 示例 1:
* 输入:
* [
* " /",
* "/ "
* ]
* 输出:2
* 解释:2x2 网格如下:
*
*
* 链接:https://leetcode-cn.com/problems/regions-cut-by-slashes
*/
public class RegionsBySlashes {
public int regionsBySlashes(String[] grid){
int N = grid.length;
// 将每个 1 * 1的方格沿两条对角线分为上下左右四部分
/**
* \ 0/
* 3/ 2\1
*/
int size = 4 * N * N;
UnionFind unionFind = new UnionFind(size);
for (int i = 0; i < N; i++){
for (int j = 0; j < N; j++){
char c = grid[i].charAt(j);
// 二维网格转为一维表格
int index = 4 * (i * N + j);
if (c == '\\'){
// 合并0,1,合并2,3
unionFind.union(index, index + 1);
unionFind.union(index + 2, index + 3);
}else if (c == '/'){
// 合并 0,3,合并1,2
unionFind.union(index, index + 3);
unionFind.union(index + 1, index + 2);
}else if (c == ' '){
unionFind.union(index, index + 1);
unionFind.union(index + 2, index + 3);
unionFind.union(index + 1, index + 2);
}
// 单元格间合并,向右合并
if (j + 1 < N){
unionFind.union(index + 1, index + 7);
}
if (i + 1 < N){
unionFind.union(index + 2, index + 4 * N);
}
}
}
return unionFind.count;
}
private class UnionFind{
private int[] parent;
private int count;
public UnionFind(int n){
this.parent = new int[n];
this.count = n;
for (int i = 0; i < n; i++) {
this.parent[i] = i;
}
}
public void union(int x, int y){
int rootX = find(x);
int rootY = find(y);
if (rootX == rootY){
return;
}
this.parent[rootX] = rootY;
this.count--;
}
public int find(int x){
return x != this.parent[x] ? find(this.parent[x]) : this.parent[x];
}
}
}
959. 由斜杠划分区域
LeetCode 959 分割区域题解
最新推荐文章于 2021-01-25 17:02:36 发布
2501

被折叠的 条评论
为什么被折叠?



