200 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:

11110
11010
11000
00000

Answer: 1

Example 2:

11000
11000
00100
00011

Answer: 3

Analysis

Solution: recursion

    public int numIslands(char[][] grid) {

        //corner case
        rowSize = grid.length;
        if(rowSize == 0) return 0;

        colSize = grid[0].length;
        int res = 0;

        for(int i=0; i<rowSize; i++) {
            for(int j=0; j<colSize; j++) {
                if(grid[i][j] == '1') {
                    res++;
                    visiteIsland(i,j,grid);
                }
            }
        }

        return res;
    }

    private void visiteIsland(int i, int j, char[][] grid) {
        //base
        if(grid[i][j] == '0') return;

        //recursion

        //visited
        grid[i][j] = '0';

        //visite neighbor
        if(i != 0) visiteIsland(i-1, j, grid);
        if(j != colSize-1) visiteIsland(i, j+1, grid);
        if(i != rowSize-1) visiteIsland(i+1, j, grid);
        if(j != 0) visiteIsland(i, j-1, grid);
    }

results matching ""

    No results matching ""