959. 由斜杠划分区域

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];
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值