Leetcode959

按照如图所示分割一个正方形,问可以分成多少块

sol:

1、并查集

  最上方编号为0,右边为1,下面为2,左边为3,根据是否是左斜线和右斜线来合并。然后左右合并,上下合并

 

public class Leetcode0959 {

    int n;
    int[] parent;

    int find(int x) {
        if (x == parent[x]) return x;
        return parent[x] = find(parent[x]);
    }

    void union(int x, int y) {
        int fx = find(x);
        int fy = find(y);
        if (fx != fy) parent[fx] = fy;
    }


    int getPos(int x, int y, int num) {
        return 4 * (x * n + y) + num;
    }

    public int regionsBySlashes(String[] grid) {
        n = grid.length;
        parent = new int[n * 4 * n];
        for (int i = 0; i < parent.length; i++) parent[i] = i;

        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[i].length(); j++) {
                char ch = grid[i].charAt(j);
                int pos0 = getPos(i, j, 0);
                int pos1 = getPos(i, j, 1);
                int pos2 = getPos(i, j, 2);
                int pos3 = getPos(i, j, 3);
                if (ch == ' ') {
                    union(pos0, pos1);
                    union(pos1, pos2);
                    union(pos2, pos3);
                } else if (ch == '/') {
                    union(pos0, pos3);
                    union(pos1, pos2);
                } else if (ch == '\\') {
                    union(pos0, pos1);
                    union(pos2, pos3);
                } else {
                    //cannot reach here
                }

                if (i > 0) {
                    int upPos = getPos(i - 1, j, 2);
                    union(pos0, upPos);
                }
                if (j > 0) {
                    int leftPos = getPos(i, j - 1, 1);
                    union(pos3, leftPos);
                }
            }
        }
        int res = 0;
        for (int i = 0; i < parent.length; i++) if (parent[i] == i) res++;
        return res;

    }

}

2、还有一种是使用dfs,这种我没有去写,有时间再试试吧

https://leetcode.com/problems/regions-cut-by-slashes/discuss/?currentPage=1&orderBy=most_votes&query=

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值