[lintcode easy]Number of Islands

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

 

 

 

posted on 2015-11-21 03:58  一心一念  阅读(136)  评论(0编辑  收藏  举报

导航