Number of Islands

Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.

  • Time: O(N!)
  • Space: O(1)
public int numIslands(char[][] grid) {
    int count = 0;
    for (int i = 0; i < grid.length; i++) {
        for (int j = 0; j < grid[0].length; j++) {
            if (grid[i][j] == '1') {
                count++;
                clearDFS(grid, i, j);
            }
        }
    }
    return count;
}

private void clearDFS(char[][] grid, int i, int j) {
    if (i < 0 || i == grid.length || j < 0 || j == grid[0].length || grid[i][j] == '0') {
        return;
    }
    grid[i][j] = '0';
    clearDFS(grid, i - 1, j);
    clearDFS(grid, i + 1, j);
    clearDFS(grid, i, j - 1);
    clearDFS(grid, i, j + 1);
}

Number of Islands II

Given m = 3, n = 3, positions = [[0,0], [0,1], [1,2], [2,1]]. We return the result as an array: [1, 1, 2, 3]

  • Time: O(N^2)
  • Space: O(N)
public class NumberofIslandsII {

    int count;
    int[] root;
    int[][] dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};

    public List<Integer> getNumIslands(int m, int n, int[][] islands) {
        root = new int[m * n];
        Arrays.fill(root, -1);
        List<Integer> ret = new ArrayList<>();
        for (int[] is : islands) {
            int index = is[0] * n + is[1];
            root[index] = index;
            count++;
            for (int[] dir : dirs) {
                int x = is[0] + dir[0];
                int y = is[1] + dir[1];
                int newIndex = x * n + y;
                if (x < 0 || y < 0 || x >= m || y >= n || root[newIndex] == -1) {
                    continue;
                }
                int rootP = find(index);
                int rootQ = find(newIndex);
                if (rootP != rootQ) {
                    root[rootP] = rootQ;
                    count--;
                }
            }
            ret.add(count);
        }
        return ret;
    }

    private int find(int p) {
        while (p != root[p]) {
            p = root[p];
        }
        return p;
    }
}

results matching ""

    No results matching ""