[LintCode] Number of Islands

468 查看

Number of Islands

Problem

Given a boolean/char 2D matrix, find the number of islands.

0 is represented as the sea, 1 is represented as the island. If two 1 is adjacent, we consider them in the same island. We only consider up/down/left/right adjacent.

Example

Given graph:

[
  [1, 1, 0, 0, 0],
  [0, 1, 0, 0, 1],
  [0, 0, 0, 1, 1],
  [0, 0, 0, 0, 0],
  [0, 0, 0, 0, 1]
]

return 3.

Note

两个for循环遍历整个矩阵,出现"1"则count++将其周围相邻的"1"全部标记为"0",用子函数mark()递归标记。

Solution

DFS

注意mark里每次递归都要判断边界。

public class Solution {
    public int numIslands(char[][] grid) {
        if (grid == null || grid.length == 0 || grid[0].length == 0) return 0;
        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++;
                    mark(grid, i, j);
                }
            }
        }
        return count;
    }
    public void mark(char[][] grid, int i, int j) {
        if (grid[i][j] == '1' && i >= 0 && i < grid.length && j >= 0 && j < grid[0].length) {
            grid[i][j] = '0';
            if (i-1 >= 0) mark(grid, i-1, j);
            if (i+1 < grid.length) mark(grid, i+1, j);
            if (j-1 >= 0) mark(grid, i, j-1);
            if (j+1 < grid[0].length) mark(grid, i, j+1);
        }
    }
}

Union Find

写一个Union Find的class,写熟练。

public class Solution {
    public int numIslands(char[][] grid) {
        if (grid == null || grid.length == 0 || grid[0].length == 0) return 0;
        int m = grid.length, n = grid[0].length;
        UnionFind uf = new UnionFind(m, n, grid);
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (grid[i][j] == '0') continue;
                int x = i*n+j;
                int y;
                if (i < m-1 && grid[i+1][j] == '1') {
                    y = x+n;
                    uf.union(x, y);
                }
                if (j < n-1 && grid[i][j+1] == '1') {
                    y = x+1;
                    uf.union(x, y);
                }
            }
        }
        return uf.count;
    }
    class UnionFind {
        public int count;
        public int[] parents;
        public UnionFind(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++;
                }
            }
            parents = new int[m*n];
            for (int i = 0; i < m*n; i++) parents[i] = i;
        }
        public int find(int i) {
            if (i == parents[i]) return i;
            parents[i] = find(parents[i]);
            return parents[i];
        }
        public void union(int i, int j) {
            int pi = find(i);
            int pj = find(j);
            if (pi == pj) return;
            else parents[pi] = pj;
            count--;
        }
    }
}

Number of Islands II