200. Number of Islands

Given an m x n 2d grid map of '1's (land) and '0's (water), return the number of islands.

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

Last updated