Number of Islands


Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
Example 1:
Input:
11110
11010
11000
00000

Output: 1
Example 2:
Input:
11000
11000
00100
00011

Output: 
 
This is one of common Google Coding question according to Leetcode.

class Solution {
    public int numIslands(char[][] grid) {
       
        int count = 0, i, j;
        for(i=0;i<grid.length;i++){
            for(j=0;j<grid[i].length;j++){
                if(grid[i][j] == '1'){
                    count += 1;
                    findSurroundings(grid, i, j);
                }
            }
        }
        return count;
    }
   
    private void findSurroundings(char[][]grid, int i, int j){
        if(i<0 || i>=grid.length || j<0 || j>=grid[i].length || grid[i][j] == '0'){
            return;
        }
        grid[i][j] = '0';
        findSurroundings(grid, i+1, j);
        findSurroundings(grid, i-1, j);
        findSurroundings(grid, i, j-1);
        findSurroundings(grid, i, j+1);
    }

Try it on Leetcode

Here, question is we have to form a island by making any horizontal or vertical land to merge and made those merged lands as water to form a island. These each islands are counted as 1.

We are going to use DFS(Depth First Search).
1) Identify a land and increments count by 1.
2) Call findSuuroundings method to check all surroundings of that particular land.
3) In this method, check all the boundary conditions of i, j and grid[i][j] as water. If any of these conditions are true then return.
4) Make current position of grid[i][j] as 0, so that it is used to form a island.
5) Then we have to check all surroundings of that particular land using recursion. ie.,
        findSurroundings(grid, i+1, j);    ---------> UP
        findSurroundings(grid, i-1, j);      ---------> DOWN
        findSurroundings(grid, i, j-1);     ---------> LEFT
        findSurroundings(grid, i, j+1);    ---------> RIGHT



Comments

Popular posts from this blog

Balanced Binary Tree

First Unique Character in a String

Majority Element

Smallest Range II