Area divided by slashes java

In an N x N grid composed of 1 x 1 squares, each 1 x 1 square is composed of /, \ or spaces. These characters divide the square into co-sided areas.

(Please note that the backslash character is escaped, so \ is represented by "\".).

Returns the number of regions.

Example 1:

Input:
[
"/",
"/"
]
Output: 2
Explanation: 2x2 grid is as follows:
Insert picture description here

Example 2:

Input:
[
"/",
" "
]
Output: 1
Explanation: 2x2 grid is as follows:
Insert picture description here

Source: LeetCode
Link: https://leetcode-cn.com/problems/regions-cut-by-slashes
Copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

ps: Another day for cv, emmmm

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

        for (int i = 0; i < n; i++) {
    
    
            for (int j = 0; j < n; j++) {
    
    
                int idx = i * n + j;
                if (i < n - 1) {
    
    
                    int bottom = idx + n;
                    merge(f, idx * 4 + 2, bottom * 4);
                }
                if (j < n - 1) {
    
    
                    int right = idx + 1;
                    merge(f, idx * 4 + 1, right * 4 + 3);
                }
                if (grid[i].charAt(j) == '/') {
    
    
                    merge(f, idx * 4, idx * 4 + 3);
                    merge(f, idx * 4 + 1, idx * 4 + 2);
                } else if (grid[i].charAt(j) == '\\') {
    
    
                    merge(f, idx * 4, idx * 4 + 1);
                    merge(f, idx * 4 + 2, idx * 4 + 3);
                } else {
    
    
                    merge(f, idx * 4, idx * 4 + 1);
                    merge(f, idx * 4 + 1, idx * 4 + 2);
                    merge(f, idx * 4 + 2, idx * 4 + 3);
                }
            }
        }

        Set<Integer> fathers = new HashSet<Integer>();
        for (int i = 0; i < n * n * 4; i++) {
    
    
            int fa = find(f, i);
            fathers.add(fa);
        }
        return fathers.size();
    }

    public int find(int[] f, int x) {
    
    
        if (f[x] == x) {
    
    
            return x;
        }
        int fa = find(f, f[x]);
        f[x] = fa;
        return fa;
    }

    public void merge(int[] f, int x, int y) {
    
    
        int fx = find(f, x);
        int fy = find(f, y);
        f[fx] = fy;
    }
}

Guess you like

Origin blog.csdn.net/weixin_43824233/article/details/113102585