clllll  

class Solution {
    public static int MAXN = 90001;

    public static int[] f = new int[MAXN];

    public static int n = 0;

    public static int union_count = 0;

    public static boolean isSameSet(int i, int j) {
        return find(i) == find(j);
    }

    public static int find(int i) {

        if (f[i] != i) {
            f[i] = find(f[i]);
        }
        return f[i];
    }

    public static void union(int i, int j) {
        int f_i = find(i);
        int f_j = find(j);
        if (f_i != f_j) {
            f[f_i] = f_j;
            union_count++;
        }
    }

    public static void build(int m, int nn) {
        for (int i = 0; i < m * nn; i++) {
            f[i] = i;
        }
        n = m;
        union_count = 0;
    }

    public static int index(int i, int j) {
        return j * n + i;
    }

    public static void main(String[] args) {
        new Solution().numIslands(new char[][] { { '1', '0', '1', '1', '0', '1', '1' } });
    }

    public int numIslands(char[][] grid) {
        // 思路:并查集。每个坐标来确定唯一的索引。
        // 每个位置判断 右边和下边的位置。是1就合并。
        int m = grid.length;
        int nn = grid[0].length;
        build(m, nn);
        int count_1 = 0;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < nn; j++) {
                // 判断是否为1,为0直接跳过
                if (grid[i][j] == '0') {
                    continue;
                }
                count_1++;// 累计1的数量
                int cur_index = index(i, j);
                // 判断 向右 是否越界 并且是1.
                if (j + 1 < nn && grid[i][j + 1] == '1') {
                    int right_index = index(i, j + 1);
                    union(cur_index, right_index);
                }
                // 判断向下是否越界。并且是1;
                if (i + 1 < m && grid[i + 1][j] == '1') {
                    int down_index = index(i + 1, j);
                    union(cur_index, down_index);
                }
            }
        }
        return count_1 - union_count;

    }
}
posted on 2024-12-02 23:46  llcl  阅读(2)  评论(0编辑  收藏  举报