首页 > 其他 > 详细

[lintcode easy]Number of Islands

时间:2015-11-21 07:02:20      阅读:276      评论:0      收藏:0      [点我收藏+]

Number of Islands

 

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

 
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

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.

 

 

The basic idea of the following solution is merging adjacent islands and the merging should be done recursively.

When an island has been visited, set it to false, and keep track of its neighbors, if the neighbors are ture, set it to false.

if it is false, return and keep tracking of the next island.

public class Solution {
    /**
     * @param grid a boolean 2D matrix
     * @return an integer
     */
    public int numIslands(boolean[][] grid) {
        // Write your code here
        // from the first[0][0]  
        // int i,j   int count to record the number of island
        if(grid.length==0 || grid[0].length==0) return 0;
        int n=grid.length;
        int m=grid[0].length;
    
        int i=0,j=0;
        int count=0;
        
        for(i=0;i<n;i++)
        {
            for(j=0;j<m;j++)
            {
                if(grid[i][j]==true)
                {
                    count++;
                    merge(grid,i,j);
                }
            }
        }
        return count;
        
    }
    public void merge(boolean[][] grid,int i, int j)
    {
        if(i<0 || j<0 || i>grid.length-1 || j>grid[0].length-1)
        return ;
        if(grid[i][j]==true) 
        {
            grid[i][j]=false;
            merge(grid,i-1,j);
            merge(grid,i+1,j);
            merge(grid,i,j-1);
            merge(grid,i,j+1);
        }
    }
}

 

 

 

[lintcode easy]Number of Islands

原文:http://www.cnblogs.com/kittyamin/p/4982863.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!