lintcode-easy-Number of Islands

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

 

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.

 

public class Solution {
    /**
     * @param grid a boolean 2D matrix
     * @return an integer
     */
    public int numIslands(boolean[][] grid) {
        // Write your code here
        if(grid == null || grid.length == 0 || grid[0] == null || grid[0].length == 0)
            return 0;
        
        int m = grid.length;
        int n = grid[0].length;
        int result = 0;
        
        for(int i = 0; i < m; i++){
            for(int j = 0; j < n; j++){
                if(grid[i][j]){
                    result++;
                    flood(grid, i, j);
                }
            }
        }
        
        return result;
    }
    
    public void flood(boolean[][] grid, int i, int j){
        grid[i][j] = false;
        
        int m = grid.length;
        int n = grid[0].length;
        
        if(i - 1 >= 0 && grid[i - 1][j])
            flood(grid, i - 1, j);
        if(i + 1 < m && grid[i + 1][j])
            flood(grid, i + 1, j);
        if(j - 1 >= 0 && grid[i][j - 1])
            flood(grid, i, j - 1);
        if(j + 1 < n && grid[i][j + 1])
            flood(grid, i, j + 1);
        
        return;
    }
    
    
}

 

posted @ 2016-03-03 07:44  哥布林工程师  阅读(174)  评论(0编辑  收藏  举报