码迷,mamicode.com
首页 > 其他好文 > 详细

lintcode-easy-Number of Islands

时间:2016-03-03 07:57:21      阅读:130      评论:0      收藏:0      [点我收藏+]

标签:

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;
    }
    
    
}

 

lintcode-easy-Number of Islands

标签:

原文地址:http://www.cnblogs.com/goblinengineer/p/5237183.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!