java 200.岛屿数量(Union Find).java

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 200.岛屿数量(Union Find).java相关的知识,希望对你有一定的参考价值。

public class Solution {
    public int numIslands(char[][] grid) {
        int count = 0;
        int n = grid.length;
        if(n == 0) return count;
        int m = grid[0].length;
        
        for(int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if(grid[i][j] == '1') {
                    DFS(grid, i, j);
                    count++;
                }
            }
        }
        return count;
        
    }
    
    private void DFS(char[][] grid, int i, int j) {
        int m = grid[0].length;
        int n = grid.length;
        if(i < 0 || j < 0 || i >= n || j >= m || grid[i][j] != '1') return;
        grid[i][j] = '0'; // indicated i,j has been visited
        DFS(grid, i - 1, j);
        DFS(grid, i + 1, j);
        DFS(grid, i, j - 1);
        DFS(grid, i, j + 1);
    }
}

/*
["11110","11010","11000","00000"]
[]
["11000","11000","00100","00011"]
*/
class UF {

public int count = 0;
public int[] id = null;

public UF(int m, int n, char[][] grid) {
    for(int i = 0; i < m; i++) {
        for(int j = 0; j < n; j++) {
            if(grid[i][j] == '1') count++;
        }
    }
    id = new int[m * n];
    for(int i = 0; i < m * n; i++) {
        id[i] = i;
    }
}

public int find(int p) {
    while(p != id[p]) {
        id[p] = id[id[p]];
        p = id[p];
    }
    return p;
}

public boolean isConnected(int p, int q) {
    int pRoot = find(p);
    int qRoot = find(q);
    if(pRoot != qRoot) return false;
    else return true;
}

public void union(int p, int q) {
    int pRoot = find(p);
    int qRoot = find(q);
    if(pRoot == qRoot) return;
    id[pRoot] = qRoot;
    count--;
}
}

public int numIslands(char[][] grid) {
    if(grid.length == 0 || grid[0].length == 0) return 0;
    int m = grid.length, n = grid[0].length;
    UF uf = new UF(m , n, grid);
    
    for(int i = 0; i < m; i++) {
        for(int j = 0; j < n; j++) {
            if(grid[i][j] == '0') continue;
            int p = i * n + j;
            int q;
            if(i > 0 && grid[i - 1][j] == '1') {
                q = p - n;
                uf.union(p, q);
            }
            if(i < m - 1 && grid[i + 1][j] == '1') {
                q = p + n;
                uf.union(p, q);
            }
            if(j > 0 && grid[i][j - 1] == '1') {
                q = p - 1;
                uf.union(p, q);
            }
            if(j < n - 1 && grid[i][j + 1] == '1') {
                q = p + 1;
                uf.union(p, q);
            }
        }
    }
    return uf.count;
}

以上是关于java 200.岛屿数量(Union Find).java的主要内容,如果未能解决你的问题,请参考以下文章

java刷题--200岛屿数量

LeetCode Java刷题笔记—200. 岛屿数量

牛客Top200---岛屿数量(java)

精选力扣500题 第41题 LeetCode 200. 岛屿数量c++/java详细题解

200. 岛屿数量(Python)

力扣 200. 岛屿数量