Number of Islands(岛屿的个数)

http://www.lintcode.com/zh-cn/problem/number-of-islands/

public class Solution {
    /**
     * @param grid a boolean 2D matrix
     * @return an integer
     */
    public int numIslands(boolean[][] grid) {
        // Write your code here
        int res = 0;
//        思路是找到一个true之后记录下来,同时把和它相邻的true全改为false,因为它们不起效了。
//        修改时使用递归简化操作
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if (grid[i][j]) {
                    res++;
                    tree(i, j, grid);
                }
            }
        }
        return res;
    }

    private void tree(int i, int j, boolean[][] grid) {
        if (i >= 0 && i < grid.length && j >= 0 && j < grid[0].length) {
            if (grid[i][j]) {
                grid[i][j] = false;
                tree(i - 1, j, grid);
                tree(i + 1, j, grid);
                tree(i, j - 1, grid);
                tree(i, j + 1, grid);
            }
        }
    }
}

你可能感兴趣的:(Number of Islands(岛屿的个数))